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.
What about an extension?
public static int MaxOrDefault<T>(this IEnumerable<T> enumeration, Func<T, int> selector)
{
return enumeration.Any() ? enumeration.Max(selector) : default(int);
}
Slightly at a tangent but perhaps still useful..another solution is to cast the value to nullable type;
var myInt = new Int[0].Max(i=>(int?)i);//myInt == null