Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting a hashtable 1

Status
Not open for further replies.

Naoise

Programmer
Dec 23, 2004
318
IE
I have a hashtable which has a key field of a unique integer and a value of a datatime. How can I order this by datetime?

Alternatively I have written the contents out to a table control, is there any way I can sort this table by datetime?

Any help appreciated. Thanks
 
hashtables are not sortable, that's one of the reasons they are effecient. instead you will need to cast (or populate a new object) which can sort.

You could populate a List<T> if you have a simple DTO for the data or you could create a datatable and sort that. I would opt for the DTO.
Code:
class MyDTO
{
   public int Key
   {
     get { return this.key; }
   }
   private int key;

   public DateTime Date
   {
     get { return this.date; }
   }
   private DateTime date;

   public MyDTO(int key, DateTime date)
   {
      this.key = key;
      this.date = date
   }
}

public IList<MyDTO> ConvertAndSortHash(HashTable hash)
{
   List<MyDTO> toReturn = new List<MyDTO>(hash.Count);
   foreach(DictionaryEntry e in hash)
   {
      toReturn.Add(new MyDTO(e.Key, e.Value));
   }
   toReturn.Sort(delegate (MyDTO dtoA, MyDTO dtoB){ return dtoA.Date.Compare(dtoB.Date); });

   return toReturn;
}

there may be some bugs. it's from memory

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
If you really need to sort, I'd suggest using a SortedList. You may be able to insert the same information into a sorted list because it implements key/value pairs as well. HashTables are most efficient for looking up or searching information based on a key.
 
WHA?!?

SortedList is a good way to go.

The other option would be to spit out the Values into a List<> and use a generic Comparer or write your own quickly if you have a more complex datatype.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top