Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ, find the minimum value of an item property, in a collection, in a dictionary

public class Item
{
  public double findMe{ get; set; } 
  public int? iMayBeNull { get; set; }
}

public Dictionary<int, ICollection<Item>> TheDictionary{ get; set; }

...

TheDictionary dict = new Dictionary<int, ICollection<Item>>();

I'm trying to find the minimum value of "findMe" where "iMayBeNull" is null in all of "dict"'s collections.

I can't seem to wrap my head around this one.

Any guidance would be greatly appreciated.

like image 255
Jeff Mitchell Avatar asked Nov 19 '25 03:11

Jeff Mitchell


2 Answers

Use .SelectMany to coalesce all the collections into one big sequence, then just use the standard .Where and .Min operators:

TheDictionary.Values
    .SelectMany(x => x)
    .Where(x => x.iMayBeNull == null)
    .Min(x => x.findMe);
like image 58
Kirk Woll Avatar answered Nov 21 '25 17:11

Kirk Woll


The LINQ expression parallel to the SelectMany method is the multiple from clause.

Example:

var seq = from col in dict.Values
            from item in col
            where item.iMayBeNull == null
            select item.findMe;

var min = seq.Min();
like image 33
GregRos Avatar answered Nov 21 '25 17:11

GregRos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!