Alex Rivera | Logout

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

Asked 2009-06-01T11:59:38.730
47

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)

Edit
Report

1 Answer

2

Without LINQ, no, there's no built-in helpers for this. You could write one though:

// I forget if you need this delegate definition -- this may be already defined in .NET 2.0
public delegate R Func<T,R>(T obj);
public static Dictionary<K,V> BuildDictionary<T,K,V>(IEnumerable<T> objs, Func<T,K> kf, Func<T,V> vf)
{
    Dictionary<K,V> d = new Dictionary<K,V>();
    foreach (T obj in objs)
    {
        d[kf(obj)] = vf(obj);
    }
    return d;
}

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

It doesn't look nearly as elegant as the LINQ-based answers, does it...

answered 2009-06-01T12:13:01.633

Your Answer