Linq to find the maximum value of List <List <int>>?

Is there a cool Linq expression to find the maximum int value in List<List<int>> ?

Currently:

 int maxValue = 0; foreach(List<int> valueRow in values) { // linq expression to get max value int value = valueRow.OfType<int>().Max(); if (value > maxValue) { maxValue = value; } } 
+4
source share
2 answers

You can use SelectMany() for this, which aligns the nested list, then you can just take the maximum of the resulting sequence:

 int maxValue = values.SelectMany( x => x).Max(); 
+12
source

Yes there is. The maximum number of each nested list can be obtained maximum:

 int maxValue = values.Max(row => row.Max()); 

On a side note: your OfType<int> not needed since the list was already List<int> .

+3
source

All Articles