So I have simple tree:
class MyNode
{
public MyNode Parent;
public IEnumerable<MyNode> Elements;
int group = 1;
}
I have a IEnumerable<MyNode>. I want to get a list of all MyNode (including inner node objects (Elements)) as one flat list Where group == 1. How to do such thing via LINQ?
You can flatten a tree like this:
You can then filter by
groupusingWhere(...).To earn some “points for style”, convert
Flattento an extension function in a static class.To earn more points for “even better style”, convert
Flattento a generic extension method that takes a tree and a function that produces descendants from a node:Call this function like this:
If you would prefer flattening in pre-order rather than in post-order, switch around the sides of the
Concat(...).