Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select the min value using linq

Tags:

c#

linq

I have a Dictionary

Dictionary<Location2D, int> h_scores = new Dictionary<Location2D, int>();

and I want to select the Key // which is Location2D by the minimum int value.

I tried

h_scores.Min().Key; // not working
h_scores.OrderBy(x => x.Value).Select(y=> y.Key).Min(); //error At least one object must implement IComparable.

so how can I select a key by the smallest int value?

like image 759
Abanoub Avatar asked Dec 17 '22 03:12

Abanoub


2 Answers

You just need to use the right overload of Min:

val minKey = h_scores.Min(s => s.Value).Key;

Update

Didn't pay attention to the return value of the overload for Min. You are definitely looking for MinBy from Jon Skeet's morelinq:

val minKey = h_scores.MinBy(s => s.Value).Key;
like image 92
Justin Niessner Avatar answered Dec 18 '22 18:12

Justin Niessner


Just for the sake of diversity, the solution which doesn't need external dependencies (e.g. MoreLinq) and is O(n) in contrast to OrderBy() solutions which are at least O(n*log(n)):

var minKey =
    h_scores.Aggregate(h_scores.First(), (min, curr) => curr.Value < min.Value ? curr : min).Key;
like image 38
Igor Korkhov Avatar answered Dec 18 '22 18:12

Igor Korkhov