Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Sorting Hashtable

0.00/5 (No votes)
5 Jun 2009 1  
This short article explains how to use DataView to sort a Hashtable

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:

  1. value ASC, key ASC
  2. value DESC, key DESC
  3. value DESC, key ASC
  4. value ASC, key DESC
  5. key ASC, value DESC
  6. 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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here