C# Error: Sequence contains no element
This error happen when I was trying to call Single() command like this:
Held holdData = new HeldBusinessLogic().Get(id: cId).Single();
Since there was no record in the Held table, the Single() command results in error: “Sequence contains no elements”
To fix the issue I had to change the code to:
Held holdData = new HeldBusinessLogic().Get(id: cId).FirstOrDefault();
The FirstOrDefault() returns null when there is no record whereas Single() tries to retrieve an element from the sequence
This error can also result when you attempt to execute any aggregate method on an empty result set.
int maxData = context.Surface.Max(s => s.Surface.GetValueOrDefault());
To fix this:
int maxData = context.Surface==null?0: context.Surface.Max(s => s.Surface.GetValueOrDefault());
Another Filter example
claim.Held.First(c => c.ClaimId == claimId);
claim.Held.FirstOrDefault(c => c.ClaimId == claimId);
However this can happen with the following commands also:
First() – use first when you know the sequence will have at least one element
FirstAsync() – Asynchronously returns the first element of a sequence.
SingleAsync() – Asynchronously returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
Last() – Returns the last element of a sequence.
LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.