I have this code:
List<int> myList = new List<int>(); var max = myList.Max(); Console.Write(max);
I want that to ensure that if there are no elements in the list it should use the default value for int
(0). But instead an InvalidOperationException
is being thrown, stating that the "Sequence contains no elements".
Of course I could use Any
or the query syntax (as in here). But I want to do it using the fluent syntax.
How can I fix this?
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
Enumerable.DefaultIfEmpty<TSource>
method anddefault
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With