1

I'm trying to find the min/max number within a nested list using Linq.

An example class would be:

public class ListA
{
    public HashSet<HashSet<int>> nestedList;

    public ListA()
    {
        nestedList = new HashSet<HashSet<int>>()
        {
            new HashSet<int> { 1, 3, 5, 7 },
            new HashSet<int> { 2, 12, 7, 19 },
            new HashSet<int> { 6, 9 , 3, 14 }
        };
    }

    public int MaxNumber
    {
        // return the highest number in list
    }
}

In the example above, the minimum number would be 1 and the max number 19.

I'm struggling to get anything to get valid syntax. Anyone help?

nvoigt
  • 75,013
  • 26
  • 93
  • 142
John Ohara
  • 2,821
  • 3
  • 28
  • 54

2 Answers2

3

SelectMany and Max will likely produce the result you desire.

Also consider using DefaultIfEmpty (with whatever default makes sense for your context) - this will ensure that Max doesn't throw an exception if nestedList is empty.

public int MaxNumber
{
    get { return nestedList.SelectMany(z => z).DefaultIfEmpty(0).Max(); }
}
mjwills
  • 23,389
  • 6
  • 40
  • 63
2
nestedList.SelectMany(item => item).Max();

and

nestedList.SelectMany(item => item).Min();
nvoigt
  • 75,013
  • 26
  • 93
  • 142