I am tying to access element but I am getting
System.InvalidOperationException: 'Sequence contains no elements
Please help - Below is the code
var highestCleredFormId = dataUpdates.Where(dat => dat.IsCleared).Select(dat => dat.ID).Max();
CodePudding user response:
The error is pretty clear - in this case dataUpdates.Where(dat => dat.IsCleared) has no elements. That is, dataUpdates has no elements where the IsCleared member has a value of true. Check if there are any elements first, and then get the max:
var clearedDataUpdates = dataUpdates.Where(dat => dat.IsCleared).ToList();
if (clearedDataUpdates.Any())
{
var highestClearedFormId = clearedDataUpdates.Select(dat => dat.ID).Max();
// ...
}
CodePudding user response:
This exception occurs when .Max() is called on an empty sequence..
Use DefaultIfEmpty before Max
var highestCleredFormId = dataUpdates
.Where(dat => dat.IsCleared)
.Select(dat => dat.ID)
.DefaultIfEmpty()
.Max();
CodePudding user response:
This is probably because dataUpdates.Where(dat => dat.IsCleared) is empty, please check if any of the object has IsCleared as true
You can have null check after Where clause
dataUpdates.Where(dat => dat.IsCleared)?.Select(dat => dat.ID).Max();
