我希望找到一种优雅的解决方案,将集合中的子集合聚合成一个大集合。我的问题在于某些子集合可能为空。
例如:
var aggregatedChildCollection = parentCollection.SelectMany(x=> x.ChildCollection);
如果子集合对象为空,这会抛出异常。一些替代方法包括:
// option 1
var aggregatedChildCollection = parentCollection
.Where(x=>x.ChildCollection != null)
.SelectMany(x => x.ChildCollection);
// option 2
var aggregatedChildCollection = parentCollection
.SelectMany(x => x.ChildCollection ?? new TypeOfChildCollection[0]);
两种方法都可以,但是我在父集合上执行了一些操作,针对大量子集合进行操作有点难以控制。
我想创建一个扩展方法,检查集合是否为空,如果为空,则像选项2那样添加一个空数组。但是我对Func的理解还不到位,不知道如何编写这个扩展方法。我知道我想要的语法应该像这样:
var aggregatedChildCollection = parentCollection.SelectManyIgnoringNull(x => x.ChildCollection);
有没有简单的扩展方法可以完成这个任务?
Enumerable.Empty<T>()
而不是剪切空集合,这样我至少会有一个空集合。 - DenverCoder9