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:
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, theDefaultIfEmpty-method will simply return the sequence itself.See the MSDN for further information
Enumerable.DefaultIfEmpty<TSource>method anddefaultkeyword in generic code.