Wednesday, May 12, 2010

Sorting a Dictionary in C# 2

During corpus processing tasks, I need to create and sort dictionaries for very simple tasks of frequency list generation. For this purpose I always have to seek on the web for solutions. C# is now at version 4 and it has lots of variations and innovations in its syntax. There are additional typing conventions, keywords, namespaces like powerful System.LINQ and extension methods. But being a linguistics student I am unable find time to upgrade my skills from C# 2005 a.k.a C# 2 to latest versions. It is not necessary perhaps also because I need C# for text processing tasks which is done very easily with C# 2 and its System.Collections.Generic namespace.
So here is a code sample which can be used to sort a dictionary with respect to its values. I have blended 2 or 3 methods into one so that it takes input as dictionary and gives output as dictionary. Code may be inefficient due to my inabilities in programming but still it works for me. Hopefully for you it would work also. :-)
public static Dictionary Sort (Dictionary dict)
{
List> list = new List>();
foreach(KeyValuePair kvp in dict)
{
list.Add(kvp);
}
list.Sort(
delegate(KeyValuePair firstPair,
KeyValuePair nextPair)
{
return nextPair.Value.CompareTo(firstPair.Value);
}
);
Dictionary d = new Dictionary();
foreach(KeyValuePair kvp in list)
{
d.Add(kvp.Key, kvp.Value);
}
return d;
}