C#LINQ SelectMany默认 [英] C# LINQ SelectMany with Default
问题描述
我正在寻找一种优雅的解决方案,将一个集合中的一个子集合聚合为一个大集合.我的问题是某些子集合可能为空.
I am looking for an elegant solution to aggregate a child collection in a collection into one large collection. My issue is when certain child collections could be null.
EG:
var aggregatedChildCollection = parentCollection.SelectMany(x=> x.ChildCollection);
如果任何子集合对象为null,则将引发异常.一些替代方法是:
This throws an exception should any of the child collection objects be null. Some alternatives are:
// 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]);
这两种方法都可以,但是我正在对父级上的许多子级集合执行某种操作,并且这变得有些不合时宜了.
Both would work but I am doing a certain operation on quite a few child collections on the parent, and it is becoming a bit unweilding.
我想创建一个扩展方法,该方法检查集合是否为null,选项2是否为null-添加一个空数组.但是,我对Func的了解还不足以使我知道如何编写此扩展方法.我确实知道我想要的语法是这样的:
What I would like is to create an extension method that checks if the collection is null and if so does what option 2 does - adds an empty array. But my understanding of Func is not to a point where I know how to code this extension method. I do know that the syntax I would like is like this:
var aggregatedChildCollection = parentCollection.SelectManyIgnoringNull(x => x.ChildCollection);
有没有一种简单的扩展方法可以实现这一目标?
Is there a simple extension method that would accomplish this?
推荐答案
您可以使用自定义扩展方法:
You can use a custom extension method:
public static IEnumerable<TResult> SelectManyIgnoringNull<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector)
{
return source.Select(selector)
.Where(e => e != null)
.SelectMany(e => e);
}
并像这样使用:
var aggregatedChildCollection = parentCollection
.SelectManyIgnoringNull(x => x.ChildCollection);
这篇关于C#LINQ SelectMany默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!