# ToDictionary

How do you convert a list of objects to a dictionary? Well, it's possible with the ToDictionary method. This may be useful when you want to have some form of lookup based on a key.

# Basic example

The first parameter of the ToDictionary method is a lambda expression specifying what the key should be. The second lambda expression specifies what the value should be.

Here we have a list of countries with CountryName, Code and Currency properties.

Let's make Code as the dictionary key, like so: arg => arg.Code and the value as the CountryName, like so: arg => arg.CountryName

When specifying the key of the dictionary, be cautious that if the list contains duplicate keys, then the ToDictionary method will throw an exception. To get round this, you can perform a Distinct operation first to remove any duplicates before using ToDictionary.

Live example: https://dotnetfiddle.net/l4jn1Q

var countries = new[]
        new {CountryName = "United Kingdom", Code = "GB", Currency = "GBP"},
        new {CountryName = "United States", Code = "US", Currency = "USD"},
        new {CountryName = "Canada", Code = "CA", Currency = "CAD"},
        new {CountryName = "France", Code = "FR", Currency = "EUR"},
        new {CountryName = "Spain", Code = "ES", Currency = "EUR"}

var results = countries.ToDictionary(arg => arg.Code, arg => arg.CountryName);

// output:
// Key:GB    Value:United Kingdom
// Key:US    Value:United States
// Key:CA    Value:Canada
// Key:FR    Value:France
// Key:ES    Value:Spain