Hashtable sorting using (possibly not unique) values

I have a hashtable that displays strings in an int. Strings are unique, but some can be matched with the same integer.

My naive approach was to simply invert the Hashtable to a SortedList, which is indexed by Hashtable values, but the problem is that you get a collision as soon as two Hashtable lines match with the same value.

What is the most efficient way to list all my Hashtable (keys and values) sorted by values? (If the two values ​​are the same, I don't care about ordering them.)

+3
source share
4 answers

Using Linq:

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

, :

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

, , . ( ).

, Hashtable KeyValuePair<K, V>... - :

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

, , , , , SortedList ( ), ( ) , (.. , ). , ( , , , ). , , ...

0

, . - , .

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.

0
source

Source: https://habr.com/ru/post/1751385/


All Articles