Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Max extension method gives an error on empty collections

Tags:

I have the following query:

var maxNumber = dbContext.Where(a => a.Id == 9).Max(a => a.Sample_Num); 

If there is no Id of 9, I get an error. I like to default the result to 0 if there is no Id of 9.

I tried:

var maxNumber = dbContext.Where(a => a.Id == 9).Max(a => a.Sample_Num) ?? 0;  

as well as other variations but was not able to get it to work

like image 729
Nate Pet Avatar asked Sep 13 '12 20:09

Nate Pet


1 Answers

You could use Any to check if there's a matching element:

int maxNumber = 0; var id9 = dbContext.Where(a => a.Id == 9); if(id9.Any()) {     maxNumber = id9.Max(a => a.Sample_Num); } 

or you could use DefaultIfEmpty(defaultValue):

int maxNumber = dbContext     .Where(a => a.Id == 9)     .Select(a => a.Sample_Num)     .DefaultIfEmpty(0)     .Max(); 
like image 121
Tim Schmelter Avatar answered Apr 05 '23 12:04

Tim Schmelter