Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequence contains no elements Error Max() [duplicate]

I am Getting:

sequence contains no elements

private int? GetPrecedingSibling(int? contentid,int? templateid) {     var value = _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid).Select(t => t.id).Max();     if (value != 0)         return value;      return null; } 
like image 445
Richard Avatar asked Aug 15 '16 13:08

Richard


1 Answers

Your query is not returning any ids. That is why the exception. If your id type is int? then use DefaultIfEmpty() like:

var value = _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid)                     .Select(t => t.id)                     .DefaultIfEmpty()                     .Max(); 

The other options is to check for Any records and then return Max or null.

var tempResult = _sequenceTemplateItemService.Query(e => e.templateId == templateid && e.contentItemId == contentid)                     .Select(t => t.id);  if (tempResult.Any()) {     return tempResult.Max(); } else {     return null; }  
like image 109
Habib Avatar answered Sep 27 '22 22:09

Habib