LINQ Max extension method gives an error on empty collections

You may try simple implementation of MaxOrDefault without need to convert anything. Just check the selector parameter inside Max function:

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

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

Just use the nullable version of Max (even though the values aggregated are not nullable): var maxNumber = dbContext.Where(a => a.Id == 9).Max(a => (int?)a.Sample_Num) ?? 0;

It is almost what Nate tried. The point is that Max of nullables gives null from an empty collection as a result, while Max of ints gives an exception as its return value is an existing int of the collection. You force it to be Max<int?> by explicitly declaring result as of that type. Then you can specify the desired default value after ??.

Tags:

C#

Linq