Skip to main content
 首页 » 编程设计

c#之连接多个集合之前进行空检查

2024年01月22日26arxive

我有以下代码,每个集合都继承自 MyCollection

var result = MyCollectionA.Concat(MyCollectionB.Concat(MyCollectionC 
             .Concat<MyCollection>(MyCollectionD))); 

在执行连接之前检查每个是否为空的最佳方法是什么?我知道我可以写出一个很大的 if else block ,但想知道是否有更好的方法

请您参考如下方法:

您可以声明一个辅助方法 EmptyIfNull并检查那里的集合是否为空,如果是则返回 Enumerable.Empty<MyCollection> .然后代码将变为:

MyCollectionA.EmptyIfNull() 
             .Concat(MyCollectionB.EmptyIfNull()) 
             .Concat(MyCollectionC.EmptyIfNull()); 

当然,如果您愿意,您可以使用更短的名称。

EmptyIfNull可以这样声明:

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