Saturday, November 15, 2008

Sorting Dictionary object in .Net

A few days ago I came across a sorting-dictionary problem at work. The easiest way to have a sorted dictionary in .Net is to use the SortedDictionary(TKey, TValue) item. Every time you enter a keyvaluepair in the SortedDictionary item, it will be sorted automatically.

But I had to sort an existing Dictionary(TKey, TValue) item, that was provided by some other program. Initially, I was hoping that there is some Dictionary.Sort() function available that I could use but there isn't.

After some research I found that you could use the List.Sort() function to sort the dictionary by keys. But that is not all. You also need to add a delegate in the List.Sort() function to carry out the sorting process.

Here is the code.

//Code takes a Dictionary<double,int> item, sorts it and return the new Dictionary<double,int> item

private static Dictionary<double,int> Sort(Dictionary<double,int> Dict)
{
//Create a List object from the Dictionary item
List<keyvaluepair<double,int>> result = new List<keyvaluepair<double,int>>(Dict);


//Use the delegate in the List.Sort function to compare the keys for sorting
result.Sort(
delegate(
KeyValuePair<double, int> first,
KeyValuePair<double, int> second)
{
return first.Key.CompareTo(second.Key);
}
);

//Add the List items into a new dictionary item
Dictionary<double,int> sortedDict = new Dictionary<double,int>();

foreach (KeyValuePair<double, int> kvp in result)
{

double key = kvp.Key;
int value = kvp.Value;

sortedDict.Add(key, value);
}

return sortedDict;
}



If there is a better way to achieve this, please let me know.