c# - 仅当第二个 TSource 不为 Null 时联合集合

标签 c# .net linq ienumerable

我有以下 linq 语句:

List<Type> allTypes = group.GetTypes().Union(group2.GetTypes()).ToList();

当 group2 为 null 时可能会抛出 NullReferenceException

解决这个问题的一种方法是在之前执行空检查,例如:

if (group2 != null)
{
    List<Type> allTypes = group.GetTypes().Union(group2.GetTypes()).ToList();
}
else 
{
   List<Type> allTypes = group.GetTypes();
}

但问题是我对不同类型有很多类似的赋值,不想以这种方式对它们中的每一个进行 if 语句,但我宁愿将空检查放在一行中,例如:

 List<Type> allTypes = group.GetTypes().Union((if group2 != null)group2.GetTypes()).ToList();

但不确定如何使用 linq 来完成。

最佳答案

这里的问题不是 TSource 为空;它是您要从中获取源的对象是 null (group2)。

您始终可以使用 Enumerable.Empty 来保存您的神奇 one liner。

List<Type> allTypes = group.GetTypes().Union(group2 != null ? group2.GetTypes() : Enumerable.Empty<Type>()).ToList();

或者您可以使用可重用的 Union 重载:

public static IEnumerable<T> Union<T>(this IEnumerable<IEnumerable<T>> source)
{
    var set = new HashSet<T>();
    foreach (var s in source)
    {
       foreach (var item in s)
       {
           if (set.Add(item))
               yield return item;
       }
    }
}

然后你的代码变成:

var allTypes = new [] { group, group2 }.Where(x => x != null).Select(x => x.GetTypes()).Union().ToList();

这种方法的优点是你可以有两个以上的序列形成一个联合。

关于c# - 仅当第二个 TSource 不为 Null 时联合集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27512664/

相关文章:

c# - MVVM中的实时UI和LiveCharts更新

c# - Windows 服务与任务计划程序 - 手动启动

c# - 奇怪的 : C# Type or Namespace name could not be found - Builds successfully

c# - 选择多个文件和文件夹所需的对话框 .NET

c# - 基于 IEnumerable<string> 过滤项目

c# - 使用多个字段过滤/搜索 - ASP.NET MVC

c# - 捕获预期异常

c# - 在 WPF 3D 中用圆柱体连接两个球体

c# - 检查通用列表内容的最佳方法

c# - 如何使用 LINQ 执行单词搜索?