Description
In regards to null
, the documentation states this:
If
TSource
is a reference type and the source sequence is empty or contains only values that arenull
, this method returnsnull
.
It also states:
If type
TSource
implements IComparable, the Max(IEnumerable) method uses that implementation to compare values. Otherwise, if typeTSource
implements IComparable, that implementation is used to compare values.
This leads me to believe that the minimum value will be calculated purely based on the output of IComparable<T>.Compare(T, T)
. That is, the output of .Min()
would be the same as .OrderBy(x => x).First()
and the output of .Max()
would be the same as .OrderBy(x => x).Last()
. Or that if Comparer<T>.Default.Compare(a, b) < 0
, then the output of new[] { a, b, }.Min()
would be a
. However, I found the following behavior instead:
Console.WriteLine($"Comparer<string>.Default.Compare(null, \"a\") == {Comparer<string>.Default.Compare(null, "a")}");
Console.WriteLine($"new[]{{ null, \"a\", }}.OrderBy(x => x).First() == {new[] { null, "a", }.OrderBy(x => x).First()}");
Console.WriteLine($"new[]{{ null, \"a\", }}.Min() == {new[] { null, "a", }.Min()}");
with output:
Comparer<string>.Default.Compare(null, "a") == -1
new[]{ null, "a", }.OrderBy(x => x).First() ==
new[]{ null, "a", }.Min() == a
By experiencing this and examining the source, I know that .Min()
and .Max()
implicitly filter out any values equal to null
as the first step (including nullable value types which box to null
). However, this is not obvious from the documentation.
May you please alter the documentation to document this behavior?
Thanks!