Linq扩展方法,如何在集合递归中查找子项 [英] Linq extension method, how to find child in collection recursive
本文介绍了Linq扩展方法,如何在集合递归中查找子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经熟悉Linq,但是对扩展方法了解甚少,我希望有人可以帮助我.
I'm already familiar with Linq but have little understanding of extension methods I'm hoping someone can help me out.
所以我有这个分层的集合伪代码,即:
So I have this hierarchical collection pseudo code ie:
class Product
prop name
prop type
prop id
prop List<Product> children
我有一个产品列表,列出产品.
And I have a list of products List products.
我是否可以通过扩展方法通过 id 在此系列中查找产品?换句话说,我在层次结构中的某处需要一个项目.
Is there any way I can look for product in this collection by the id with a extension method ? In other words I need one item somewhere within the hierarchy.
推荐答案
这里是一种通用解决方案,一旦找到匹配项,它将缩短对层次结构的遍历.
Here is a generic solution that will short-circuit traversal of the hierarchy once a match is found.
public static class MyExtensions
{
public static T FirstOrDefaultFromMany<T>(
this IEnumerable<T> source, Func<T, IEnumerable<T>> childrenSelector,
Predicate<T> condition)
{
// return default if no items
if(source == null || !source.Any()) return default(T);
// return result if found and stop traversing hierarchy
var attempt = source.FirstOrDefault(t => condition(t));
if(!Equals(attempt,default(T))) return attempt;
// recursively call this function on lower levels of the
// hierarchy until a match is found or the hierarchy is exhausted
return source.SelectMany(childrenSelector)
.FirstOrDefaultFromMany(childrenSelector, condition);
}
}
要在您的情况下使用它:
To use it in your case:
var matchingProduct = products.FirstOrDefaultFromMany(p => p.children, p => p.Id == 27);
这篇关于Linq扩展方法,如何在集合递归中查找子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文