ToDictionary

suggest change

ToDictionary builds a dictionary from an IEnumerable. The key selector must return a unique key for each element. If two elements produce the same key, ToDictionary throws ArgumentException. Other overloads also take a value selector.

var persons = new[] {
    new { Name="Fizz", Id=1},
    new { Name="Buzz", Id=2},
    new { Name="Foo", Id=3},
    new { Name="Bar", Id=4},
};

A key selector alone stores each original element as the value. The dictionary's value type is the element type, which here is an anonymous type, not object.

var personsById = persons.ToDictionary(p => p.Id);
// personsById is a Dictionary<int, anonymous type>

Console.WriteLine(personsById[1].Name); //Fizz
Console.WriteLine(personsById[2].Name); //Buzz

A value selector stores that function's return value instead of the original element.

var namesById = persons.ToDictionary(p => p.Id, p => p.Name);
//namesById is a Dictionary<int,string>

Console.WriteLine(namesById[3]); //Foo
Console.WriteLine(namesById[4]); //Bar

As stated above, the keys returned by the key selector must be unique. The following will throw an exception.

var persons = new[] {
    new { Name="Fizz", Id=1},
    new { Name="Buzz", Id=2},
    new { Name="Foo", Id=3},
    new { Name="Bar", Id=4},
    new { Name="Oops", Id=4}
};

var willThrowException = persons.ToDictionary(p => p.Id);

If the source does not have a unique key, use ToLookup instead. A lookup pairs each key with every matching element.

Feedback about page:

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



Table Of Contents