Home > Backend Development > C++ > How Can LINQ Flatten a Tree Structure and Filter by a Specific Property?

How Can LINQ Flatten a Tree Structure and Filter by a Specific Property?

Mary-Kate Olsen
Release: 2025-01-29 00:56:12
Original
767 people have browsed it

How Can LINQ Flatten a Tree Structure and Filter by a Specific Property?

Use linq to show flat tree structure

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>
Copy after login
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 show the tree -like structure, we can use Linq's SelectMany computing to retrieve all offspring of each node. The following Flatten extension method is obtained and the input elements are available and their Elements attributes are flattened recursively:

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template