Tuesday, July 1, 2014

Sorting a HashTable object using LINQ in .NET

In .NET, you can't directly sort a Hashtable object. A tip on sorting a Hashtable object is to cast it to Dictionary then apply LINQ OrderBy() method to the Hashtable object. See examples below:
VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Private Sub SortHashTableKey()
 
        hash = New Hashtable()
        hash.Add("B", 1)
        hash.Add("A", 2)
        hash.Add("C", 3)
 
        Dim dict = hash.Cast(Of DictionaryEntry)() _
                        .ToDictionary(Function(d) d.Key, Function(d) d.Value) _
                        .OrderBy(Function(e) e.Key)
 
        Console.WriteLine("Sort by Key")
        For Each item In dict.ToList()
            Console.WriteLine(String.Format("{0}, {1}", item.Key, item.Value))
        Next
 
        Console.WriteLine(Environment.NewLine)
 
    End Sub
 
    Private Sub SortHashTableValue()
        hash = New Hashtable()
        hash.Add("A", 2)
        hash.Add("B", 1)
        hash.Add("C", 3)
 
        Dim dict = hash.Cast(Of DictionaryEntry)() _
                   .ToDictionary(Function(d) d.Key, Function(d) d.Value) _
                   .OrderBy(Function(e) e.Value)
        Console.WriteLine("Sort by Value")
        For Each item In dict.ToList()
            Console.WriteLine(String.Format("{0}, {1}", item.Key, item.Value))
        Next
 
    End Sub

C#
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private void SortHashTableKey() {
 Hashtable hash = new Hashtable();
 hash.Add("B", 1);
 hash.Add("A", 2);
 hash.Add("C", 3);

 var dict = hash.Cast < DictionaryEntry > ()
  .ToDictionary(d => d.Key, d => d.Value)
  .OrderBy(e => e.Key);

 listBox1.Items.Add("Sort by Key");

 foreach(var item in dict.ToList()) {
  listBox1.Items.Add(String.Format("{0}, {1}",
   item.Key, item.Value));
 }

 listBox1.Items.Add(Environment.NewLine);
}

private void SortHashTableValue() {
 Hashtable hash = new Hashtable();
 hash.Add("B", 1);
 hash.Add("A", 2);
 hash.Add("C", 3);

 var dict = hash.Cast < DictionaryEntry > ()
  .ToDictionary(d => d.Key, d => d.Value)
  .OrderBy(e => e.Value);

 listBox1.Items.Add("Sort by Value");

 foreach(var item in dict.ToList()) {
  listBox1.Items.Add(String.Format("{0}, {1}",
   item.Key, item.Value));
 }
}

Output:

Cheers! :)

0 comments:

Post a Comment