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 ?
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 ?
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: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.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.
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.
Aggregate
Using the mighty
Aggregate
method.I know that
MinBy
is cleaner in this case, but withAggregate
you have more power and its built-in. ;)