'How to Get max value from IEnumerable
IEnumerable<DataGridViewRow> l_selectedRowobj = this.dataGridView1.SelectedRows.Cast<DataGridViewRow>().OrderBy(abc => abc.Index);
l_selectedRowobj.Max();
l_selectedRowobj.Max(); I get a NULL value at this line
I dont want to use List for getting max count like below:
List<int> listofRowIndex = new List<int>();
foreach (DataGridViewRow row in l_selectedRowobj)
{
listofRowIndex.Add(row.Index);
}
int maxrowind = listofRowIndex.Max();
Solution 1:[1]
You need to check if the sequence contains any elements first - if it does, then you can get Max value from that sequence by given property:
if (l_selectedRowobj.Any())
{
int max = l_selectedRowobj.Max(row => row.Index);
}
or this if you want to assign some value to max in case the sequence is empty:
int max = l_selectedRowobj.Any() ? l_selectedRowobj.Max(row => row.Index) : 0;
Solution 2:[2]
You should give your .Max() method a clue which property it should use to compare against the others and find the biggest one:
int max = l_selectedRowobj.Max(row => row.Index);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | moritzg |
