Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

.net-4.0

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?

like image 676
Royi Namir Avatar asked Nov 08 '12 08:11

Royi Namir


2 Answers

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.
like image 157
Spontifixus Avatar answered Sep 29 '22 04:09

Spontifixus


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); } 
like image 43
Alvaro Rivoir Avatar answered Sep 29 '22 03:09

Alvaro Rivoir