Bookmark and Share

IEnumerable<T>.ToDictionary()

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.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.