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.)
Using Linq:
hashtable.Cast<DictionaryEntry>().OrderBy(entry => entry.Value).ToList()
, :
myhashtable.Keys.Select(k => new List<string, int>() {k, myhashtable[k]}) .OrderBy(item => item[1]);
, , . ( ).
, Hashtable KeyValuePair<K, V>... - :
KeyValuePair<K, V>
myhashtable.Items.OrderBy(kvp => kvp.Value);
, , , , , SortedList ( ), ( ) , (.. , ). , ( , , , ). , , ...
, . - , .
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.
Source: https://habr.com/ru/post/1751385/More articles:How to get related item from ASP.NET repeater - c #WPF TextBox потерял фокус как прикрепленное свойство - wpfThe difference between std :: tr1 :: array and boost :: array - c ++Is the HTTPS client-server security method "fairly secure"? - securityReading and Writing Calendar - androidLua C api: How to load lua files defined as modules? - cChoose the most frequent from the column in - mysqlTesting if an object has been freed - objective-cGetting the identity of the row I just inserted - sqlWhy is my MySQL query so slow? - phpAll Articles