开发者

How does IEnumerable .Min handle Nullable types?

So, IEnumerable uses the IComparable interface to eva开发者_运维问答luation a call to .Min(). I'm having trouble finding whether or not the nullable types support this. Assuming I have a list of int?, {null, 1, 2}. Will .Min() work?


Yes, it works.

The value null is neither greater than nor less than any non-null value - at least for the built in types. So the null values will effectively be ignored in Min or Max calculation unless all the values are null.


The following program

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        List<int?> l = new List<int?>() {1, null, 2};
        Console.WriteLine(l.Min());
    }
}

outputs 1. If the list is however empty, or contains only null, the output is null.

So null counts as the biggest int for Min.


The null values are ignored:

static void Main()
{
    var values = new int?[] { null, 1, 2 };
    Console.WriteLine(values.Min());
}

prints 1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜