How to make LINQ’s Max-function return the default value if the sequence is empty?

Try this:

var myList = new List<int>();
var max = myList.DefaultIfEmpty().Max();
Console.Write(max);

LINQ’s DefaultIfEmpty-method checks if the sequence is empty. If that is the case, it will return a singleton sequence: A sequence containing exactly one element. This one element has the default value of the sequence’s type. If the sequence does contain elements, the DefaultIfEmpty-method will simply return the sequence itself.

See the MSDN for further information

  • on the Enumerable.DefaultIfEmpty<TSource> method and
  • the default keyword in generic code.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)