Royi Namir
Royi Namir

Reputation: 148544

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

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?

Upvotes: 47

Views: 21313

Answers (5)

Bill Stanton
Bill Stanton

Reputation: 69

If you use Enumerable.Aggregate, you won't need any special handling for the empty list case. Try this:

List<int> myList = new List<int>();
var max = myList.Aggregate(default(int), (seed, i) => (i > seed ? i : seed));
Console.Write(max);

Upvotes: 4

paolo antonelli
paolo antonelli

Reputation: 101

As an extension method, the solution of @AlvaroRivoir can be extendend with further generalization adding another type parameter:

public static K MaxOrDefault<T, K>(this IEnumerable<T> enumeration, Func<T, K> selector) {
    return enumeration.Any() ? enumeration.Max(selector) : default;
}

Upvotes: 0

Alvaro Rivoir
Alvaro Rivoir

Reputation: 401

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);
}

Upvotes: 9

Spontifixus
Spontifixus

Reputation: 6660

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

Upvotes: 108

Myles McDonnell
Myles McDonnell

Reputation: 13335

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

Upvotes: 4

Related Questions