IEnumerable .Min如何处理Nullable类型?

Rus*_*een 8 c#

因此,IEnumerable使用IComparable接口来评估对.Min()的调用.我无法确定可空类型是否支持此功能.假设我有一个int?,{null,1,2}的列表.Will .Min()有效吗?

Mar*_*ers 13

是的,它有效.

该值null既不大于也不小于任何非空值 - 至少对于内置类型.因此,除非所有值都是,否则将在MinMax计算中有效地忽略空值null.


Vla*_*lad 8

下面的程序

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

输出1.如果列表为空或仅包含null,则输出为null.

所以null算是最大intMin.