Home >Backend Development >C++ >How Can LINQ Flatten a Tree Structure and Filter by a Specific Property?
In software development, data that is tissue into a tree -like structure is often required. A common task is to convert trees to flat lists or sets. This can be implemented using a language integration query (linq) framework in the .NET.
Assuming that we have the following simple tree structure expressed by the MyNode class:
We get an Ienumeration
<code class="language-csharp">class MyNode { public MyNode Parent; public IEnumerable<MyNode> Elements; public int Group { get; set; } }</code>and want to get the list of all nodes (including internal nodes) in the tree as a single flat list. In addition, we hope to filter this list, only the node with a group attribute equal to 1.
In order to follow the list of leflation of the group, we can use the where operator:
<code class="language-csharp">public static IEnumerable<MyNode> Flatten(this IEnumerable<MyNode> elements) => elements.SelectMany(c => Flatten(c.Elements)).Concat(elements);</code>
This solution is effective and elegantly flattened, and the unwanted nodes are filtered out according to the Group attributes.
<code class="language-csharp">var flattenedList = treeElements.Flatten().Where(node => node.Group == 1);</code>
The above is the detailed content of How Can LINQ Flatten a Tree Structure and Filter by a Specific Property?. For more information, please follow other related articles on the PHP Chinese website!