pelicano
pelicano

Reputation: 51

minimum value in dictionary using linq

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 ?

Upvotes: 4

Views: 9090

Answers (4)

Nappy
Nappy

Reputation: 3046

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. ;)

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500225

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.

Upvotes: 2

Beep beep
Beep beep

Reputation: 19151

    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));

Upvotes: 2

Ani
Ani

Reputation: 113402

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.

Upvotes: 4

Related Questions