Using LINQ, find the minimum value of the item property, in the collection, in the 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 am trying to find the minimum value of "findMe", where "iMayBeNull" is null in all collections of "dict".

I don’t seem to wrap my head around it.

Everyone is welcome any guide.

+3
source share
2 answers

Use .SelectManyto combine all collections into one large sequence, and then simply use the standard operators .Whereand .Min:

TheDictionary.Values
    .SelectMany(x => x)
    .Where(x => x.iMayBeNull == null)
    .Min(x => x.findMe);
+7
source

A LINQ expression parallel to a method SelectManyis a 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();
+1
source

All Articles