Thursday, July 31, 2008

.Net Dictionary Sort

Ever wish the .Net Dictionary generic supported sorting like List?
Roni Schuetz had the great idea to just leverage the sorting capabilities of the List.
Roni Schuetz: sorting dictionary by value

He did it in a type-specific way, but I'm taking it a step further - making it generic like List and Dictionary.
Here's a C# Dictionary generic that supports sorting by a Sort() method just like the List generic:
Note: Just like List, the Value type must support sorting (implement IComparable), this is enforced by the "where".

public class SortableDictionary<TKey, TValue> : Dictionary<TKey,
TValue>
where TValue : IComparable
{
// Sorting
public void Sort()
{
// Copy the dictionary data to a List
List<KeyValuePair<TKey, TValue>> sortedList = new List<KeyValuePair<TKey, TValue>>(this);
// Use the List's Sort method, and make sure we are comparing Values.
sortedList.Sort(
delegate(KeyValuePair<TKey, TValue> first, KeyValuePair<TKey, TValue> second) { return first.Value.CompareTo(second.Value); }
);
// Clear the dictionary and repopulate it from the List
this.Clear();
foreach (KeyValuePair<TKey, TValue> kvp in sortedList)
this.Add(kvp.Key, kvp.Value);
}
}