Skip to content

Enumerable.Min<TSource>() documentation should mention null filtering behavior #7923

Open
@binki

Description

@binki

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 are null, this method returns null.

It also states:

If type TSource implements IComparable, the Max(IEnumerable) method uses that implementation to compare values. Otherwise, if type TSource 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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Pri3Indicates issues/PRs that are low priorityarea-System.Linqdoc-bugProblem with the content; needs to be fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions