Sorting a HashTable by value

Posted on 2005-05-06
Last Modified: 2008-01-09
I need to sort a hashtable by its values. There are duplicate value for the keys in the table, but it doesn't matter. All that's important is that the key-value relationship is maintained and the values are sorted from lowest to highest (they're Integer values in my case). If what I want to do is impossible or there is a better way to do what I need, please let me know what else I can do.  All I really need is a list that holds pairs of integer values, one unique and one not unique, sorted by the not unique column.
Question by:btrieve
    LVL 23

    Expert Comment

    Dim values As New Hashtable

    Dim list As New ArrayList(values.Keys)
    Dim keys As Integer() = DirectCast(list.ToArray(GetType(Integer)),Integer())

    Dim value As Object
    For Each key As Integer In keys
      value = values(key)
    LVL 23

    Expert Comment

    The other is to use a SortedList.

    Author Comment

    Wouldn't this be sorting the HashTable by its keys rather then values???
    LVL 23

    Expert Comment

    Dim table As New Hashtable
    Dim list As New ArrayList(table.Values)
    Dim values As Integer() = DirectCast(list.ToArray(GetType(Integer)),Integer())
    LVL 23

    Expert Comment

    i misread and thought you wanted to sort the keys...

    Author Comment

    I tried something like that but my problem arises in trying to make the sorting of the values apply to the keys as well so that when I iterate throught the hashtable it has the same correspondence of keys to values, but ordered descending by values.

    if my hashtable looks like this originally:

    I need my hashtable to look like this after sorting:

    Like I said, I'm not really sure if this is possible using hashtables, so if there's some other way to do this with some kind of name-value pair collection, I'd be happy to take suggestions.
    LVL 62

    Accepted Solution

    The Hash Table is probably not what you want to use. Think of a hash table as a number of buckets that hold elements, key and value pairs. The hash table puts these elements in a particular bucket by some analysis it does on the elements key. So let say you have a hash table with 10 buckets and 100 elements divided among the buckets. Now let say you ask the hash table to return the value for the element with a key of “Tool”. The hash function determines that if this key is in the hash table it will be found in bucket 6. In bucket 6 let say there are only 15 elements to search through. So to determine if the key is in the table the most number of compares will be 15 in comparison to the 100 elements in the table. The max number of elements and the load factor determines the number of buckets in the hash table.

    What I would do is use the array list to store the information in.

    Create you structure as follows:

    Structure MyList
        Implements IComparable

        Public Key As Integer
        Public Value As Integer

          ‘ We must show Arraylist how to compare you object
        Public Function CompareTo(ByVal obj As Object) _
            As Integer Implements System.IComparable.CompareTo

            Dim tmpObj As MyList

            tmpObj = CType(obj, MyList)
            Return Me.Value.CompareTo(tmpObj.Value)

        End Function

    End Structure

    Dim MyArrayList As New ArrayList
    Dim MyElement As New MyList

    By defining “Implements IComparable” and implementing the function CompareTo in your structure, when you call ArrayList.Sort and ArrayList.BinarySearch, your CompareTo function will be called. Because you know the structure and know how you want to sort and search your objects, you pass those items to the system which knows how to compare the integers. The Me.Key in the return statement above is the first interger to compare to the tempObj.integer the other integer which ArrayList.Sort or ArrayList.BinarySearch sent to be compare.

    Before you can call ArrayList.BinarySearch the object must be sorted, the ArrayList.Sort will do that for you.

    And now the rest of the code:

    ' Call sort before calling MyArrayList.BinarySearch

    ' The index into the ArrayList where it
    ' found the record you wanted.
    Dim index As Integer
    ' Holds the item you are searching for.
    Dim tmpRecord As New MyList

    tmpRecord.Value = CInt(txtFind.Text.ToString())
    index = MyArrayList.BinarySearch(tmpRecord)

    ‘ To Access the value of the wanted key
    Dim Value As Integer

    Value = MyArrayList(index).Value

    Also to add valuea to the MyArrayList is done like this.

    MyElement.Key = 23
    MyElement.Value = 456


    The value of index will be a negative number meaning it was not found or a positive number meaning the zero based index of the value you were looking for in your arraylist.

    Hope this was of some help.

    Author Comment

    Thanks so much, I've practically gone bald from staring at this all day. I had been thinking along those lines, but I haven't been working with VB.NET long enough to be comfortable with structures. They still scare me for no good reason. In other words, not only did you answer my question but you may have made me a better programmer on top of it now that I know how easy this can be. Thanks again, you're awesome!!!

    Featured Post

    Courses: Start Training Online With Pros, Today

    Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

    Join & Write a Comment

    Article by: Kraeven
    Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
    Introduction When many people think of the WebBrowser ( control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    25 Experts available now in Live!

    Get 1:1 Help Now