MinOrDefault extension is not supported
I just would like to confirm that
开发者_如何学编程Collection.Min(p => p.Value);
Works only if the Collection is not empty and there is no MinOrEmpty or something similar, right ?
If you want it to return the default value for the element type if it's empty, that's easy:
var min = Collection.Select(p => p.Value).DefaultIfEmpty().Min();
Alternatively, if you want a particular minimum value:
var min = Collection.Select(p => p.Value)
.Concat(Enumerable.Repeat(int.Minvalue, 1)
.Min();
Or:
var min = Collection.Select(p => (int?) p.Value)
.Min(); // min will be the null value if Collection is empty
Is that what you're after? It's not entirely clear.
Min
and Max
behave slightly differently for empty sequences of non-nullable element types than for empty sequences of nullable element types. When the element type is nullable, the null value is returned if and only if the sequence is empty; for non-nullable element types, InvalidOperationException
is thrown. See my Edulinq blog post on Min/Max for more details.
If the collection contains nullable types -- either reference types or Nullable<T>
values -- then the Min
method will return null
if the collection is empty.
If the collection contains non-nullable value types then the Min
method will throw an InvalidOperationException
if the collection is empty.
Note that in your example, where you're passing a delegate to the Min
method, then the behaviour is determined by the delegate's return type, not the type of the elements themselves.
(And no, there's no built-in MinOrEmpty
method. There are plenty of easy alternatives though, see Jon's answer for details.)
If the sequence is empty is does not make sense to compute the minimum value. However, if you want to return a specific value if the sequence is empty you can do it like this (assuming that your a computing the minimum of int
values):
int defaultMinValue = -1;
var min = Collection.Select(p => p.Value).DefaultIfEmpty(defaultMinValue).Min();
If the sequence is empty it will return -1, otherwise it will compute the the minimum value of the sequence.
精彩评论