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);
}
}
4 comments:
This is great work. I took the liberty of making Ascending and Descending methods to save trouble later. Keep up the good work! Have you ever considered posting a complete solution of sorting by key and value, with the Ascending and Descending methods?
Zack, Many thanks! You solved my dilemma of retrieving data from a DataList which the user modified on screen, sorting it (with your SortedDictionary, and writing the results to a XML file.
Gary Stafford
Lazer Incorporated
very nice
Here there be dragons: the documentation of Dictionary(Of TKey, TValue) states that the order in which its items are enumerated is unspecified. Consequently, re-adding all of the elements in the sort order is not guaranteed to do anything; even if it works as designed now, it might not in the future.
Post a Comment