Home >Backend Development >C++ >How to Flatten a Hierarchical Tree Structure into a Flat List Using LINQ?

How to Flatten a Hierarchical Tree Structure into a Flat List Using LINQ?

Linda Hamilton
Linda HamiltonOriginal
2025-01-29 00:46:10337browse

How to Flatten a Hierarchical Tree Structure into a Flat List Using LINQ?

The structure of the flat display of 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

In order to achieve this flattelling, the following Linq expression can be used:

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

method filter list, and only select the node of

.

The additional style enhancement

Where(...) group == 1 In order to improve readability,

Method can be defined as an extension function in static class:
<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!

Statement:
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