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?

2

2 Answers 2

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(); } } 
Sign up to request clarification or add additional context in comments.

Comments

2
nestedList.SelectMany(item => item).Max(); 

and

nestedList.SelectMany(item => item).Min(); 

1 Comment

How embarrassing - I was trying to use a second Select after SelectMany - thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.