c# Hashtable sorted by Keys

强颜欢笑 提交于 2019-11-30 20:27:13

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

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);
}

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>.

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]);
}

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()]));
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!