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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With