Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c# - 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?

question from:https://stackoverflow.com/questions/13284933/how-to-make-linqs-max-function-return-the-default-value-if-the-sequence-is-empt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...