Donate

Sorting A HashTable Object Using LINQ In C#.NET And VB.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:
Sorting A HashTable Object Using LINQ In C#.NET And VB.NET
Cheers! :)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.