Choose min value using linq

I have a dictionary

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

and I want to select 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 the key with the smallest int value?

+4
source share
4 answers

You just need to use the correct Min overload:

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

Strike>

Update

I did not pay attention to the return value of the overload for Min. You are definitely looking for MinBy from Jon Skeet morelinq:

 val minKey = h_scores.MinBy(s => s.Value).Key; 
+7
source

Just for a change, a solution that does not need external dependencies (for example, MoreLinq) and O (n), unlike 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; 
+3
source

If you order them using Value , the first will be with a minimum

 h_scores.OrderBy(x => x.Value).First().Select(y=> y.Key); 
+1
source

I do not know what Location2D is, but you can use the following example to do what you want. Just sub in your class instead of string. In addition, since the values ​​are not guaranteed to be unique in the dictionary (but may be in your case), you most likely want to do .Single () in the key enumeration.

 [Test] public void Test() { var dictionary = new Dictionary<string, int> { { "first", 2 }, { "second", 1 }, { "third", 3 }, { "fourth", 1 } }; int min = dictionary.Values.Min(); IEnumerable<string> keys = dictionary.Keys.Where(key => dictionary[key] == min); Assert.That(keys.Count(), Is.EqualTo(2)); Assert.That(keys.Contains("second"), Is.True); Assert.That(keys.Contains("fourth"), Is.True); } 
+1
source

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


All Articles