Friday, July 10, 2009

Aggregate a generic List into a generic Dictionary using LINQ

Let's say I have a a generic list of contacts, where contacts are instances of my class Contact:

class Contact {
public string Name { get; set; }
public string StreetAddress { get; set; }
public string ZipCode { get; set; }
.....
}

List myContacts = new List();
//add instances of Contact.

Now what if I want to aggregate the contacts by ZipCode (or by some other external values like contact type, and store the aggregated results in a generic Dictionary, with the GROUP BY values as the keys and the list items as the values? It's pretty straightforward when the List has primitive types, but not when it's a class like what I have. Here's one way to convert:

List<Contact> contacts = new List<Contact>();

//add some instances of Contact

Dictionary<string, List<Contact>> contactsByLocation = new Dictionary<string, List<Contact>>();

var result = (from c in contacts

group c by m.ZipCode into g

select new { g.Key, g }).ToDictionary(g => g.Key, g => g.g);

foreach (string s in result.Keys)

{

IGrouping<string, IndexModification> temp = result[s];

List<IndexModification> items = temp.ToList<IndexModification>();

contactsByLocation.Add(s, items);

}


I have to say this is much more cumbersome than I like. Hopefully I can find a better way do this later.