Reputation: 2393
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
Upvotes: 7
Views: 65226
Reputation: 1460
I used a list to store keys of Hashtable and sorted it and then dislayed Hashtable using this sorted list. Here is my code:
List<string> lst = new List<string>(); foreach (var key2 in ht.Keys) { lst.Add(key2.ToString()); } lst.Sort(); foreach (var item in lst) { Console.WriteLine(string.Format("{0},{1}", item, ht[item.ToString()])); }
Upvotes: 0
Reputation: 463
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
Upvotes: 6
Reputation: 12157
Use a list instead of a hash (or convert your hash to a dictionary), and do this:
var dictionary = new Dictionary<string, int>();
var l = dictionary.Keys.ToList();
l.Sort();
foreach (var key in l)
{
Console.WriteLine(dictionary[key]);
}
Upvotes: 1
Reputation: 160922
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
Upvotes: 17
Reputation: 18359
Using Linq is easy (using System.Linq
):
var sortedList = (from kv in MyDictionary select kv order by kv.Key).ToList<KeyValuePair<string, int>>();
That returns a list of KeyValuePair<string, int>
.
Upvotes: 0
Reputation: 726639
Because of the nature of hash tables, you cannot sort them on the key in place: they organize their keys in buckets based on their hash code, a value outside of hash table's control. However, you can read key-value pairs in whatever order that you like. Here is how you can do it using LINQ:
IDictionary<string, int> d = ...; // your hash table
var ordered = d.OrderBy(p => p.Key).ToList();
foreach (var p in ordered) {
Console.WriteLine("Key: {0} Value: {1}", p.Key, p.Value);
}
Upvotes: 2