You're using
.Where(...) .DefaultIfEmpty()
which means that if there are no results, pretend it with a single zero result. Then you try to use this null result when calling Max ...
Perhaps you can change it to:
return tGreenSheet.Where(gs => ...) .Max(gs => (int?) Convert.ToInt32(...)) ?? 0;
Does it use overload by maximizing int? values int? , and returns int? null int? null if there were no values. Then ?? 0 ?? 0 converts this null value to 0. At least that LINQ to Objects behavior ... you will need to check if it gives the same result for you.
Of course you do not need to use ?? 0 ?? 0 , if you gladly change the method signature to return an int? . This will provide additional information, as the caller can then determine the difference between βno dataβ and βsome data with a maximum value of 0β:
return tGreenSheet.Where(gs => ...) .Max(gs => (int?) Convert.ToInt32(...));
Another option is to use the DefaultIfEmpty() overload, which takes a value - like this:
return tGreenSheet.Where(gs => ...) .Select(gs => Convert.ToInt32(...)) .DefaultIfEmpty(0) .Max();
source share