ToDictionary C# with Example



ToDictionary C# with Example

The ToDictionary() LINQ method can be used to generate a Dictionary collection based on a 
given IEnumerable source. 
IEnumerable users = GetUsers(); 
Dictionary usersById = users.ToDictionary(x => x.Id); 
In this example, the single argument passed to ToDictionary is of type Func, which returns the 
key for each element. 
This is a concise way to perform the following operation: 
Dictionary usersById = new Dictionary(); 
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 
and returns the Value to be added for each entry. 
IEnumerable users = GetUsers(); 
Dictionary 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 users = GetUsers(); 
Dictionary 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. 

0 Comment's

Comment Form

Submit Comment