Assume that there is a layered tree data structure represented by the
class, each of which has a parent node, a sub -node collection, and a group of identifier. Essence
MyNode
Challenge
The goal is to obtain a list of all objects, including parent nodes and sub -nodes, as a single flat list. However, only nodes should be included in the results list.
Solution MyNode
group == 1
This expression is recursive throughout the tree structure, and the exhibition is flattened as a single list. It selects all sub -nodes of the given node and calls
to generate recursively. Then connect this sequence to the current node to generate the merger table.Filter
IEnumerable<MyNode> Flatten(IEnumerable<MyNode> e) => e.SelectMany(c => Flatten(c.Elements)).Concat(e);
Flatten
Once the tree is flattened, you can use the
.
<加> The additional style enhancement Where(...)
group == 1
In order to improve readability,
var result = flattenedNodes.Where(n => n.group == 1);
<泛> Found implementation
In order to generalize the flat process, it can create a generic expansion method. It accepts a tree structure and a function to generate off the offspring from the node: Flatten
public static IEnumerable<MyNode> Flatten(this IEnumerable<MyNode> e) => e.SelectMany(c => c.Elements.Flatten()).Concat(e);
To implement this generic type, just call the method and provide the corresponding functions to extract the offspring:
The above is the detailed content of How to Flatten a Hierarchical Tree Structure into a Flat List Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!