So I have simple tree:
class MyNode
{
public MyNode Parent;
public IEnumerable Elements;
int group = 1;
}
I have a I
You can flatten a tree like this:
IEnumerable Flatten(IEnumerable e) =>
e.SelectMany(c => Flatten(c.Elements)).Concat(new[] { e });
You can then filter by group
using Where(...)
.
To earn some "points for style", convert Flatten
to an extension function in a static class.
public static IEnumerable Flatten(this IEnumerable e) =>
e.SelectMany(c => c.Elements.Flatten()).Concat(e);
To earn more points for "even better style", convert Flatten
to a generic extension method that takes a tree and a function that produces descendants from a node:
public static IEnumerable Flatten(
this IEnumerable e
, Func> f
) => e.SelectMany(c => f(c).Flatten(f)).Concat(e);
Call this function like this:
IEnumerable tree = ....
var res = tree.Flatten(node => node.Elements);
If you would prefer flattening in pre-order rather than in post-order, switch around the sides of the Concat(...)
.