Minimum value in a dictionary using linq

I have a type dictionary

Dictionary<DateTime,double> dictionary 

How can I get the minimum value and the key corresponding to this value from this dictionary using linq?

+4
source share
4 answers
 var min = dictionary.OrderBy(kvp => kvp.Value).First(); var minKey = min.Key; var minValue = min.Value; 

It is not very effective; You might want to consider the MoreLinq MinBy extension method .

If you run this query very often, you may need to consider a different data structure.

+4
source

Cumulative

 var minPair = dictionary.Aggregate((p1, p2) => (p1.Value < p2.Value) ? p1 : p2); 

Using the powerful Aggregate method.

I know that MinBy cleaner in this case, but with Aggregate you have more power and built-in .;)

+4
source
  Dictionary<DateTime, double> dictionary; //... double min = dictionary.Min(x => x.Value); var minMatchingKVPs = dictionary.Where(x => x.Value == min); 

You could combine it, of course, if you really wanted to do it on one line, but I think the above is easier to read.

  var minMatchingKVPs = dictionary.Where(x => x.Value == dictionary.Min(y => y.Value)); 
+2
source

You cannot easily do this efficiently in regular LINQ - you can get the minimum value easily, but another scan is required to find the key. If you can afford it, use Jess's answer.

However, you can watch MinBy on MoreLINQ , which will let you write:

 var pair = dictionary.MinBy(x => x.Value); 

After a single scan, you will have a pair with a key and value.

EDIT: As the Diaper says, MinBy also in System.Interactive in Reactive Extensions .

+2
source

All Articles