Elegant way to go from list of objects to dictionary with two of the properties

leora picture leora · Jun 1, 2009 · Viewed 46.3k times · Source

i seem to write this code over and over again and wanted to see if there was a better way of doing it more generically.

I start out with a list of Foo objects

Foo[] foos = GenerateFoos();

I think want to create a dictionary where the key and value are both properties of Foo

for example:

Dictionary<string, string> fooDict = new Dictionary<string, string>():
foreach (Foo foo in foos)
{
    fooDict[foo.Name] = foo.StreetAddress;
}

is there anyway of writing this code generically as it seems like a basic template where there is an array of objects, a key property a value property and a dictionary.

Any suggestions?

I am using VS 2005 (C#, 2.0)

Answer

Marc Gravell picture Marc Gravell · Jun 1, 2009

With LINQ:

var fooDict = foos.ToDictionary(x=>x.Name,x=>x.StreetAddress);

(and yes, fooDict is Dictionary<string, string>)


edit to show the pain in VS2005:

Dictionary<string, string> fooDict =
    Program.ToDictionary<Foo, string, string>(foos,
        delegate(Foo foo) { return foo.Name; },
        delegate(Foo foo) { return foo.StreetAddress; });

where you have (in Program):

public static Dictionary<TKey, TValue> ToDictionary<TSource, TKey, TValue>(
    IEnumerable<TSource> items,
    Converter<TSource, TKey> keySelector,
    Converter<TSource, TValue> valueSelector)
{
    Dictionary<TKey, TValue> result = new Dictionary<TKey, TValue>();
    foreach (TSource item in items)
    {
        result.Add(keySelector(item), valueSelector(item));
    }
    return result;
}