When retrieving data from web services, it’s sometimes obvious it was meant to be represented as a dictionary. In my coworkers case earlier today, he was getting back a simple class from a web service written in Java (don’t blame me for the exposed fields).
public class KeyValuePairType
{
public string Key;
public string Value;
}
He wanted to access the values as nature (err, C#) intended it:Dictionary<string, string>. Since the data was being returned as an array of KeyValuePairTypes with unique values on the key, this was quite simple with LINQ.
var dataDictionary = additionalData.ToDictionary(k => k.Key, v => v.Value);
This is a great way to create a dictionary out a key/value pair scenario, but the syntax is even easier for your keyed business objects. For example, assume you have an enumerable of clients with an Id property. You want to have a dictionary of these clients so you can easily access them without the hassle of tons of LINQ statements.
var clientDictionary = clients.ToDictionary(c => c.Id);
The definition of clientDictionary is Dictionary<int, Client>, allowing you easy access to the client values.
The other two overloads of the ToDictionary method require one to create a class that implements IEqualityComparer. This comparer is used to determined if the key is already in the dictionary. EqualityComparer<T>.Default is used in the previous overloads.