简体   繁体   English

按(可能是非唯一的)值对Hashtable进行排序

[英]Sort Hashtable by (possibly non-unique) values

I have a Hashtable that maps strings to ints. 我有一个将字符串映射到整数的Hashtable。 Strings are unique, but several may be mapped to the same integer. 字符串是唯一的,但有几个可以映射到相同的整数。

My naive approach was to simply invert the Hashtable to a SortedList that is indexed by the Hashtable's values, but the problem is that you get a clash as soon as two of the Hashtable's strings map to the same value. 我天真的方法是简单地将Hashtable反转为由Hashtable的值索引的SortedList,但问题是只要两个Hashtable的字符串映射到相同的值,就会发生冲突。

What is the most efficient way to list my entire Hashtable (keys and values) ordered by the values? 列出由值排序的整个Hashtable(键和值)的最有效方法是什么? (Where two values are the same, I don't care about their ordering.) (如果两个值相同,我不关心它们的排序。)

使用Linq:

hashtable.Cast<DictionaryEntry>().OrderBy(entry => entry.Value).ToList()

You said you wanted the most efficient method. 你说你想要最有效的方法。 The following code is the best I could find. 以下代码是我能找到的最好的代码。

Hashtable hashtable = GetYourHashtable();
var result = new List<DictionaryEntry>(hashtable.Count);
foreach (DictionaryEntry entry in hashtable)
{
    result.Add(entry);
}
result.Sort(
    (x, y) =>
    {
        IComparable comparable = x.Value as IComparable;
        if (comparable != null)
        {
            return comparable.CompareTo(y.Value);
        }
        return 0;
    });
foreach (DictionaryEntry entry in result)
{
  Console.WriteLine(entry.Key.ToString() + ":" + entry.Value.ToString());
}

I experimented with various different approaches using Linq, but the above method was about 25-50% faster. 我使用Linq尝试了各种不同的方法,但上述方法的速度提高了约25-50%。

Maybe this could work: 也许这可行:

myhashtable.Keys.Select(k => new List<string, int>() {k, myhashtable[k]})
    .OrderBy(item => item[1]);

This should give you a list of lists, with the nested lists containing exactly two elements, the key and the value. 这应该给你一个列表列表,嵌套列表包含两个元素,键和值。 Sorted by the value (second element). 按值排序(第二个元素)。

I'm not quite sure if the Hashtable has a KeyValuePair<K, V> type... something like this could also work: 我不太确定Hashtable是否有KeyValuePair<K, V>类型......这样的东西也可以工作:

myhashtable.Items.OrderBy(kvp => kvp.Value);

The immediate way that springs to mind is along the lines of what you have except that you have a SortedList (or similar) that uses the original values (ie the integers) as keys and as values has a list of the original keys (ie the strings if I understand correctly). 脑海中浮现的直接方式是你所拥有的,除了你有一个SortedList(或类似的)使用原始值(即整数)作为键和值有一个原始键的列表(即如果我理解正确的字符串)。 There is a bit more faff involved in adding values (since you need to check if they exist and add them to the list if so or create a new list otherwise). 添加值有更多的麻烦(因为你需要检查它们是否存在并将它们添加到列表中,如果是这样或者另外创建一个新列表)。 There may be better methods but this is the one that immediately springs to mind... 可能有更好的方法,但这是一个立即浮现在脑海中的方法......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM