Friday, November 6, 2015

C# - Fix Sequence contains no elements

This is very common error which can occur when you dealing with any kind of list/IQueryable etc. Root cause of this issue is when you apply filter/aggregate function (e.g. Max, Min etc.) to the list, it is empty. To avoid this kind of we can follow various ways to check list is empty or not. Otherwise we can fetch “FirstOrDefault” element rather than taking “First” element. 

Example

Exception:


-----------------------------System Exception Content-------------------------------
System.InvalidOperationException: Sequence contains no elements
   at System.Linq.Enumerable.Max(IEnumerable`1 source)
   at System.Linq.Enumerable.Max[TSource](IEnumerable`1 source, Func`2 selector)



 Code Snippet which cause this issue:


int compSteps=0;
if (appCompletedSteps.Count > 0)
{
compSteps = appCompletedSteps.Where(x => x.AppNumber == application.AppNumber).Max(y => y.StepID);
}


Code Fix: 

int compSteps=0;
if (appCompletedSteps.Count > 0 && appCompletedSteps.Where(x => x.AppNumber == app.AppNumber).Any())
{
compSteps = appCompletedSteps.Where(x => x.AppNumber == app.AppNumber).Max(y => y.StepID);
} 

No comments:

Post a Comment