My favoriate piece of code for this week...

time to read 5 min | 889 words

I found that I need to group a collection by a certain attribute of its member quite often. Usually because I'm trying to do some crazy things with deeply nested and timed to put some data on the screen.

Anyway, here is the code:

public static IDictionary<T, ICollection<K>> GroupBy<K, T>(ICollection<K> collection, Converter<K, T> converter)

{

       Dictionary<T, ICollection<K>> dic = new Dictionary<T, ICollection<K>>();

       foreach (K k in collection)

       {

              T key = converter(k);

              if (dic.ContainsKey(key) == false)

              {

                     dic[key] = new List<K>();

              }

              dic[key].Add(k);

       }

       return dic;

}

It is not earth shattering or anything like it, but it is going to make a lot of tasks a lot easier now.

(BTW, this is now a part of Rhino Commons).