Use the linq flat -shaped tree structure and filter according to the attribute
In the field of tree -shaped data, it is often necessary to convert the hierarchical structure to a flat list. Suppose you have a layered classmode with the Parent and Elements attributes, and you want to flatten the trees by extracting all the Mynode instances in a single list. Specifically, you are only interested in getting nodes that are equal to 1 in the Group.
The following linq query provides you with a solution:
<code class="language-c#">var flatList = rootNodes.SelectMany(node => Flatten(node.Elements)).Concat(rootNodes).Where(node => node.group == 1);</code>
The following is its working principle:
selectmany (node = & gt; flatten (node.elements)) - : This method recursively flattened the Elements collection of each MyNode to obtain the flat list of all offspring.
Concat (rootnodes)
: Connect the flat list of offspring to the original Mynodes list. -
Where (node = & gt; node.group == 1) : Filter the flat list, which only contains nodes with a group attribute 1.
-
In order to improve the readability of the code, please consider using the expansion method for flattening:
Then use your tree calling expansion method, and specify how to retrieve offspring:
<code class="language-c#">public static IEnumerable<T> Flatten<T>(this IEnumerable<T> e, Func<T, IEnumerable<T>> f) => e.SelectMany(c => f(c).Flatten(f)).Concat(e);</code>
Enjoy the benefits brought by the use of linq flat level data!
The above is the detailed content of How Can I Flatten a Tree Structure and Filter by a Property 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