tags:

views:

59

answers:

3

Hi guys,

How do you SortDictionary by value (.NET 2.0)? Or is there any alternative to this?

I am trying to sort Tags just like in blogger. But I want to sort the Tags by number there were used, not by name?

+2  A: 

You can use a lambda function and a List to do something like:

var myList = new Dictionary<string, int>();
var result = new List<KeyValuePair<string, int>>(myList);
result.Sort((first, second) => second.Value.CompareTo(first.Value));
Thomas
+1 This method will also allow you to provide different sorting options by just using an alternate lambda function.
Grant Peters
A: 

Thanks Thomas

Is this the correct way of enumerating the result?

foreach (KeyValuePair<string, int> pair in result) {Console.WriteLine(pair.Value);}

It's descending though so I used the result.Reverse();

Nullstr1ng
result.Reverse() will take another milliseconds of calculation. Is that the efficient way of enumerating it?
Nullstr1ng
A: 

I have to ask again .. why this code wont work when used in ASP.NET

result.Sort((first, second) => second.Value.CompareTo(first.Value));

it throws 5 errors while building

Nullstr1ng