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.
I'm just refactoring dtb's solution to make it more generic. Try this Extension method:
And you can use it like this:
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:
Here is a generic solution that will short-circuit traversal of the hierarchy once a match is found.
To use it in your case:
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:
An alternative solution using the yield to optimize the enumerations needed.
Then you can find a match by calling something like FirstOrDefault: