Home >Backend Development >C++ >How to Flatten a Hierarchical Tree Structure into a Flat List Using LINQ?
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
<code class="language-csharp">IEnumerable<MyNode> Flatten(IEnumerable<MyNode> e) => e.SelectMany(c => Flatten(c.Elements)).Concat(e);</code>
Flatten
Once the tree is flattened, you can use the
.
The additional style enhancement Where(...)
group == 1
In order to improve readability,
<code class="language-csharp">var result = flattenedNodes.Where(n => n.group == 1);</code>
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
<code class="language-csharp">public static IEnumerable<MyNode> Flatten(this IEnumerable<MyNode> e) => e.SelectMany(c => c.Elements.Flatten()).Concat(e);</code>This method allows the exhibition to flatten any layered data structure, provided that a function is defined to retrieve off the offspring nodes from each element.
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!