LINQ max sequence contains no elements C# .NET

3 months ago / mcchu28

You may encounter the following error when you are using LINQ Max function when sequence contains no elements.

System.InvalidOperationException : Sequence contains no elements
at System.Linq.Enumerable.Max(IEnumerable`1 source)

In the following example, I try to get the maximum year from the list of models. You can check using Any function to see if the list of models are empty first before calling the Max function.

List models = GetModels();
if (!models.Any())
return models;
var latestYear = models.Max(x => x.Year);