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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With