.NET - Effectively sorting <key, value> pairs by value

So, I'm looking for the most efficient way to sort a bunch pairs<string, float>by value, because I need to get the 3 highest records from a large number of pairs.

My natural reaction was to use sortedList, but apparently it is only sorted by key, and I cannot use the reverse list solution, because I know that the strings are unique, but the floats may not be like that.

Any simple and effective solution that I am missing?

+3
source share
7 answers

, - , . O (n), O (n log n)... .

O (n log n), , , LINQ:

var ordered = pairs.OrderBy(pair => pair.Value).Take(3).ToList();

, - :

public static IEnumerable<TSource> TakeTop<TSource, TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     int count)

O (n * count). , ...

+13

linq:

yourDictionary.OrderBy(kv => kv.Value).Take(3);

, , , .

+2
+2

, , :

List<KeyValuePair<string,float>> myList = new List<KeyValuePair<string,float>>():

... //adding whatever...

myList.Sort(delegate(KeyValuePair<string,float> pair1, KeyValuePair<string,float> pair2) { return pair1.Value.CompareTo(pair2.Value); });
0

- , C5:

using Bag = C5.TreeBag<C5.KeyValuePair<string, float>>;
using Comparer = C5.DelegateComparer<C5.KeyValuePair<string, float>>;

...

var bag = new Bag(new Comparer(
  (pair1, pair2) => 
    pair1.Value == pair2.Value ? 
    pair1.Key.CompareTo(pair2.Key) :
    // inverted because you need the highest entries 
    pair2.Value.CompareTo(pair1.Value))); 

...

var topN = bag.Take(N).ToList();

( ) O (log n).

0

Jons

public static IEnumerable<TSource> TakeTop<TSource, TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     int count)
{
  var top = source.Take(count).OrderBy(keySelector).ToArray();
  var last = count-1;
  foreach(var item in source.skip(count))
  {
    if(keySelector(top[last]) < keySelector(item))
    {
      top[last] = item;
      //depending on count this might be faster as buble sort
      top = top.OrderBy(keySelector).ToArray();
    }
  }
  return top;
}

, "" SO:)

0

- , / ( - , )

0

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


All Articles