将 IEnumerable<T?> 转换为 IEnumerable<T>

时间:2021-02-03 16:19:48

标签: c#

我希望能够获取可空类型 T? 的列表,并删除任何空值,留下 T 类型。例如:

        List<int?> xs = new List<int?>() {1, 2, 3};
        
        // this method works
        IEnumerable<int> xs2 = xs.Select(x => x ?? 0);
        
        // this method does not
        IEnumerable<int> xs3 = xs.Where(x => x != null);

我很欣赏 C# 无法推断列表的类型,因此它能够判断列表中没有空值。但是我正在努力寻找最好的方法来做到这一点,而不仅仅是像这样进行显式转换:

IEnumerable<int> xs3 = xs.Where(x => x != null).Select(x => (int)x);

我遇到的问题是,如果 Where 语句不存在,那么代码仍会通过类型检查,但会出现运行时错误。有没有办法在 C# 中做到这一点,以便在编译时,我可以保证列表的类型不可为空,并且它不包含空值?

dotnetfiddle

理想情况下,我希望以通用方式执行此操作(但我有一个单独的问题)。

我设法找到了 this question,它提供了一种通过将空值转换为类型值来转换值的好方法。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用.Value

IEnumerable<int> xs3 = xs.Where(x => x != null).Select(x => x.Value);