7

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

nawfal
  • 70,104
  • 56
  • 326
  • 368
s15199d
  • 7,261
  • 11
  • 43
  • 70

2 Answers2

4

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

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

The issues reported above were due to improper looping.

Community
  • 1
  • 1
s15199d
  • 7,261
  • 11
  • 43
  • 70
0

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
  • 2,403
  • 1
  • 18
  • 23
  • 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 Apr 20 '10 at 13:31
  • Error message: Class 'CountValueComparer' must implement 'Function Compare(x As Object, y As Object) As Integer' for interface 'System.Collections.IComparer'. – s15199d Apr 20 '10 at 13:31