Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Hashtable sorted by Keys

I have a hashtable with keys in alphabetic and values in numeric. how to sort the hashtable based on keys?

ExchangeA, 200
ExchangeV, 100
ExchangeC, 200

to be like this

ExchangeA, 200
ExchangeC, 200
ExchangeV, 100
like image 215
John Ryann Avatar asked Feb 14 '12 16:02

John Ryann


2 Answers

You can use a SortedDictionary for this which will do the sorting by key for you. In your case a SortedDictionary<string, int> would work:

SortedDictionary<string, int> dict = new SortedDictionary<string, int>();
dict.Add("Exchange C", 200);
dict.Add("Exchange A", 200);
dict.Add("Exchange V", 100);

foreach (var kvp in dict)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

Output:

Key = Exchange A, Value = 200
Key = Exchange C, Value = 200
Key = Exchange V, Value = 100
like image 164
BrokenGlass Avatar answered Sep 21 '22 02:09

BrokenGlass


The simplest way I found to "sort" hashtable is:

var hash = new Hashtable();
var orderedKeys = hash.Keys.Cast<string>().OrderBy(c => c); // supposing you're using string keys
var allKvp = from x in orderedKeys select new{ key = x, value = hash[x] };

However, Im not ordering the original hashtable, only reading its values in an ordered way.

As in other replies, if you need to store your data is sorted way, the best is to use SortedDictionary

like image 41
Rafael Diego Nicoletti Avatar answered Sep 23 '22 02:09

Rafael Diego Nicoletti