Nate Pet Nate Pet - 4 months ago 27
C# Question

LINQ Max extension method gives an error on empty collections

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

Answer Source

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();