Friday, September 5, 2008

Sorting a Dictionary by its value

There are a number of ways of sorting a generic dictionary, and searching the net will result in a lot of painful 2.0 approaches. as of .Net 3.5 the two approaches are:


var byteOcccurance = new Dictionary<byte, int>();
// populate byteOccurrance
foreach (byte b in bytes)
{
if (!byteOcccurance.ContainsKey(b))
byteOcccurance.Add(b, 0);

byteOcccurance[b]++;
}
// draw histogram
foreach (var entry in byteOcccurance.OrderByDescending(entry => entry.Value))
Console.WriteLine("{0,3} {1} {2}",
entry.Key, entry.Value, new String('*', entry.Value / 10));

// or using LINQ

foreach (var entry in from pair in byteOcccurance orderby pair.Value ascending select pair)
Console.WriteLine("{0,3} {1} {2}",
entry.Key, entry.Value, new String('*', entry.Value / 10));

No comments: