Sort dictionary by value

I have a dictionary in the form:

{ "honda" : 4, "toyota": 7, "ford" : 3, "chevy": 10 } 

I want to sort it by the second column aka (value) in descending order.

Required Conclusion:

"chevy", 10

"toyota", 7

honda 4

"ford", 3

+6
sorting dictionary
source share
2 answers

Thanks to caryden from: How do you sort the dictionary by value?

 Dim sortedDict = (From entry In dict Order By entry.Value Descending Select entry) 

The above problems are caused by the wrong cycle.

+4
source share

Actually, if it is a HashTable, it cannot be sorted. On the other hand, if you have an ArrayList or any other collection that can be sorted, you can implement your own IComparer.

  public class MyDicComparer : IComparer { public int Compare(Object x, Object y) { int Num1= ((Dictionary)x).Value; // or whatever int Num2= ((Dictionary)y).Value; if (Num1 < Num2) return 1; if (Nun1 > Num2) return -1; return 0; // Equals, must be consideres } ArrayList AL; ... AL.Sort(MyDicComparer); 

NTN

0
source share

All Articles