[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


Sorting a HashTable by value

Posted on 2005-05-06
Medium Priority
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
  • 4
  • 3
LVL 23

Expert Comment

ID: 13946143
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

ID: 13946148
The other is to use a SortedList.

Author Comment

ID: 13946322
Wouldn't this be sorting the HashTable by its keys rather then values???

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

LVL 23

Expert Comment

ID: 13946338
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

ID: 13946339
i misread and thought you wanted to sort the keys...

Author Comment

ID: 13946463
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 64

Accepted Solution

Fernando Soto earned 2000 total points
ID: 13947179
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

ID: 13947459
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
Integration Management Part 2
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month19 days, 17 hours left to enroll

872 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