Get KeyValuePair from KeyvaluePairs list with minimum value

I need to get Kvp from the list List<KeyValuePair<Int, Int>> depending on the minimum value.

I tried this:

 KeyValuePair<Int, Int> kvp= listOfKvps.Min(e=> e.Key); 

but this only returns the value, not the KeyValuePair integer that I need.

+4
source share
3 answers

There is no built-in MinBy method, so you can either write the MinBy extension method or simply .OrderBy(x => x.Key).First() . A MinBy will be O(n) , so it will be more efficient - but more code to write; p

For example, you can use:

 var kvp= listOfKvps.MinBy(e=> e.Key); 

with:

 public static class SomeUtil { public static TSource MinBy<TSource, TValue>( this IEnumerable<TSource> source, Func<TSource, TValue> selector) { using (var iter = source.GetEnumerator()) { if (!iter.MoveNext()) throw new InvalidOperationException("no data"); var comparer = Comparer<TValue>.Default; var minItem = iter.Current; var minValue = selector(minItem); while (iter.MoveNext()) { var item = iter.Current; var value = selector(item); if (comparer.Compare(minValue, value) > 0) { minItem = item; minValue = value; } } return minItem; } } } 
+5
source
 var min = listOfKvps.OrderBy(kvp => kvp.Key).First(); 

If you want to do this with one O (n) passing through the sequence, instead of requiring O (n log n) ordering, you can do it like this:

 var min = listOfKvps.Aggregate((agg, kvp) => (kvp.Key < agg.Key) ? kvp : agg); 

(Of course, the second version is much less readable / intuitive than the first, even if it has a higher theoretical performance. It would be wiser to use some MinBy method: either write your own, use the version from Marc's answer, or use the version from MoreLINQ . )

+5
source

I would suggest using the MinBy extension MinBy from MoreLinq .

As an alternative:

 var minKey = listOfKvps.Min(kvp => kvp.Key); var minKvp = listOfKvps.First(kvp => kvp.Key == minKey); 

This is still O(n) , although it requires 2 passes over the list. Sorting the list and selecting the first item is more complicated, but it is O(n * logn) , which can make a difference for large lists.

+1
source

All Articles