Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 724
pelicano Avatar asked Dec 16 '22 21:12

pelicano


2 Answers

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.

like image 137
Ani Avatar answered Jan 10 '23 01:01

Ani


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

like image 45
Nappy Avatar answered Jan 09 '23 23:01

Nappy