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?
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With