tags:

views:

190

answers:

3

I have a dictionary in the form of: { "honda" : 4, "toyota": 7, "ford" : 3, "chevy": 10 }

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

Desired output:

"chevy", 10

"toyota", 7

"honda", 4

"ford", 3

+1  A: 

http://stackoverflow.com/questions/289/how-do-you-sort-a-c-dictionary-by-value

Jarek
Thanks for the link Jarek. I tried the solution with the most votes (38), and that didn't seem to work.Here's an excerpt of the output from that:GLO007BKLG , 141060LE2X , 174280GRXLRG , 173287GR38 , 1631264482 , 13021U , 1832002B , 141060ST2X , 1FF420006 , 1E02320105EW , 159128WH , 19954 , 153001BK , 140004BKLG , 1DTR125 , 153000BK , 29056037BK , 2853103FC , 2753100AC , 2215OFFWEB , 1910OFFWEB , 1759227BKLG , 1415JAN09 , 1320OFF150 , 13CJ AFFILIATES , 1248035BKLG , 1053109BR , 8GOOGLE ADWORDS , 7
s15199d
A: 

Actually, if it is HashTable, it can not 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);  

HTH

Daniel Dolz
Get an error on "implements IComparer": Public Class MyDictComparer Implements IComparer Public Function Compare(ByVal x As [Object], ByVal y As [Object]) As Integer Dim Num1 As DictionaryEntry = DirectCast(x, DictionaryEntry) Dim Num2 As DictionaryEntry = DirectCast(y, DictionaryEntry) If CInt(Num1.Value) < CInt(Num2.Value) Then Return 1 End If If CInt(Num1.Value) > CInt(Num2.Value) Then Return -1 End If Return 0 End Function End Class
s15199d
Error message: Class 'CountValueComparer' must implement 'Function Compare(x As Object, y As Object) As Integer' for interface 'System.Collections.IComparer'.
s15199d
A: 

Thanks to caryden from: http://stackoverflow.com/questions/289/how-do-you-sort-a-c-dictionary-by-value/1332#1332

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

The issues reported above were due to improper looping.

s15199d