4

I have a dictionary of type

Dictionary<DateTime,double> dictionary

How can I retrive a minimum value and key coresponding to this value from this dictionary using linq ?

pelicano
  • 51
  • 2
  • 3
  • possible duplicate of [How to use LINQ to select object with minimum or maximum property value](http://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value) – nawfal Jul 19 '14 at 18:39

4 Answers4

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

This is not very efficient though; you might want to consider MoreLinq's MinBy extension method.

If you are performing this query very often, you might want to consider a different data-structure.

Ani
  • 111,048
  • 26
  • 262
  • 307
4

Aggregate

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

Using the mighty Aggregate method.

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

Nappy
  • 3,016
  • 27
  • 39
2
    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 felt like doing 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));
Beep beep
  • 18,873
  • 12
  • 63
  • 78
  • 3
    The one line version has O(n^2) efficiency - it will find the minimum value in the dictionary *on every pair*. – Jon Skeet Sep 06 '10 at 19:57
2

You can't easily do this efficiently in normal LINQ - you can get the minimal value easily, but finding the key requires another scan through. If you can afford that, use Jess's answer.

However, you might want to have a look at MinBy in MoreLINQ which would let you write:

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

You'd then have the pair with both the key and the value in, after just a single scan.

EDIT: As Nappy says, MinBy is also in System.Interactive in Reactive Extensions.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194