Linq扩展方法,如何在集合中递归查找子级
我已经熟悉 Linq 但对扩展方法知之甚少,我希望有人可以帮助我。
所以我有这个分层集合伪代码,即:
class Product
prop name
prop type
prop id
prop List<Product> children
我有一个产品列表列出产品。
有什么方法可以通过扩展方法通过 id 在此集合中查找产品吗?换句话说,我需要层次结构中某处的一项。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一个通用解决方案,一旦找到匹配项,就会短路层次结构的遍历。
要在您的情况下使用它:
Here is a generic solution that will short-circuit traversal of the hierarchy once a match is found.
To use it in your case:
您可以使用此扩展方法展平树结构:
用法:
请注意,这可能不是很快。如果您反复需要通过 id 查找产品,请创建一个字典:
You can flatten your tree structure using this extension method:
Usage:
Note that this is probably not very fast. If you repeatedly need to find a product by id, create a dictionary:
我只是重构 dtb 的解决方案以使其更加通用。尝试这个扩展方法:
你可以像这样使用它:
I'm just refactoring dtb's solution to make it more generic. Try this Extension method:
And you can use it like this:
另一种解决方案是使用产量来优化所需的枚举。
然后你可以通过调用类似 FirstOrDefault 的方法来查找匹配项:
An alternative solution using the yield to optimize the enumerations needed.
Then you can find a match by calling something like FirstOrDefault:
如果您想要“子迭代”并在产品列表中查找子项:
您可以使用现有的
SelectMany
扩展方法。 SelectMany 可用于“展平”两级层次结构。以下是对 SelectMany 的精彩解释:http://team.interknowlogy.com/blogs/danhanan/archive/2008/10/10/use-linq-s-selectmany-method-to-quot-flatten -quot-collections.aspx
您的语法如下所示:
If you want to "sub-iterate" and find a child in a list of Products:
You can use the existing
SelectMany
extension method. SelectMany can be used to "flatten" a two-level hierarchy.Here's a great explanation of SelectMany: http://team.interknowlogy.com/blogs/danhanan/archive/2008/10/10/use-linq-s-selectmany-method-to-quot-flatten-quot-collections.aspx
Your syntax would like like this: