Introduction
I like using Hashtable
, but unfortunately it does not come with Sort functionality. This short article explains how to use DataView
to sort the Hashtable
. This method allows you to sort not only by key and by value, but also in descending or ascending order.
Using the Code
Here is the function that takes a Hashtable
, converts it to a DataView
and then sorts it (value DESC, key ASC).
Private Function SortHashtable(ByVal oHash As Hashtable) As DataView
Dim oTable As New Data.DataTable
oTable.Columns.Add(New Data.DataColumn("key"))
oTable.Columns.Add(New Data.DataColumn("value"))
For Each oEntry As Collections.DictionaryEntry In oHash
Dim oDataRow As DataRow = oTable.NewRow()
oDataRow("key") = oEntry.Key
oDataRow("value") = oEntry.Value
oTable.Rows.Add(oDataRow)
Next
Dim oDataView As DataView = New DataView(oTable)
oDataView.Sort = "value DESC, key ASC"
Return oDataView
End Function
Note that there are many sorting combinations you can have like:
- value ASC, key ASC
- value DESC, key DESC
- value DESC, key ASC
- value ASC, key DESC
- key ASC, value DESC
- key DESC, value ASC
Here is the code that uses this SortHashtable()
function:
Dim oHash As New Hashtable
oHash.Add("Anna", "2")
oHash.Add("Sam", "3")
oHash.Add("Mary", "5")
oHash.Add("Alice", "4")
oHash.Add("Nicole", "2")
Dim oDataView As DataView = SortHashtable(oHash)
For iRow As Long = 0 To oDataView.Count - 1
Dim sKey As String = oDataView(iRow)("key")
Dim sValue As String = oDataView(iRow)("value")
Next
History
- 5th June, 2009: Initial post