c# - 将空值转换为空 IEnumerable<T> 的 Linq 方法?

标签 c# linq ienumerable

我正在处理一些从第 3 方 API 返回给我的数组。有时这些返回为 null。除了 null 情况外,我能够使用 LINQ 优雅地处理所有事情。我想到了这样的事情:

IEnumerable<Thing> procs = APICall(foo, bar);
var result = from proc in procs ?? Enumerable.Empty<Thing>()
    where proc != null
    select Transform(proc);

此处合并运算符的使用有点令人恼火。我是否遗漏了 LINQ 中处理此问题的内容?

最佳答案

这实际上与您的解决方案相同,但我使用了扩展方法。

public static partial class EnumerableExtensions
{
    public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
    {
        return source ?? Enumerable.Empty<T>();
    }
}

所以我们最终得到:

IEnumerable<Thing> procs = APICall(foo, bar);
var result = from proc in procs.EmptyIfNull()
             where proc != null
             select Transform(proc);

关于c# - 将空值转换为空 IEnumerable<T> 的 Linq 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6115524/

相关文章:

c# - 如何使用 JSONConvert 将变量 Result 转换为对象?

c# - C# 中的 SQL 依赖

c# - 带有链接子报表的 Crystal 报表仅适用于报表预览

c# - LINQ to SQL 查询未返回正确的日期时间

asp.net - ASP.Net/C#,在页面上的某些控件之间循环?

c# - 无需等待所有任务完成即可访问 Enumerable.Range 中的结果

javascript - 如何从 Javascript 解密身份验证 Cookie

c# - 这个 "listMerging"代码可以改进吗?

c# - 为什么 Enumerable 不继承自 IEnumerable<T>

c# - IEnumerable 不在 foreach 中枚举