ToDictionary

suggest change

The ToDictionary() LINQ method can be used to generate a Dictionary<TKey, TElement> collection based on a given IEnumerable<T> source.

IEnumerable<User> users = GetUsers();
Dictionary<int, User> usersById = users.ToDictionary(x => x.Id);

In this example, the single argument passed to ToDictionary is of type Func<TSource, TKey>, which returns the key for each element.

This is a concise way to perform the following operation:

Dictionary<int, User> usersById = new Dictionary<int User>();
foreach (User u in users) 
{
  usersById.Add(u.Id, u);
}

You can also pass a second parameter to the ToDictionary method, which is of type Func<TSource, TElement> and returns the Value to be added for each entry.

IEnumerable<User> users = GetUsers();
Dictionary<int, string> userNamesById = users.ToDictionary(x => x.Id, x => x.Name);

It is also possible to specify the IComparer that is used to compare key values. This can be useful when the key is a string and you want it to match case-insensitive.

IEnumerable<User> users = GetUsers();
Dictionary<string, User> usersByCaseInsenstiveName = users.ToDictionary(x => x.Name, StringComparer.InvariantCultureIgnoreCase);

var user1 = usersByCaseInsenstiveName["john"];
var user2 = usersByCaseInsenstiveName["JOHN"];
user1 == user2; // Returns true

Note: the ToDictionary method requires all keys to be unique, there must be no duplicate keys. If there are, then an exception is thrown: ArgumentException: An item with the same key has already been added. If you have a scenario where you know that you will have multiple elements with the same key, then you are better off using ToLookup instead.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


LINQ Queries:
* Except
* Any
* JOINS
* Zip
* All
* Basics
* Where
* Sum
* ToDictionary
* Concat
* Union

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
64 LINQ Queries
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script