In the tree -like data structure, the flat list of nodes is often required from the nested level. For example, consider a "MyNode" object with the "Elements" attribute, which contains a sub -node collection. In order to obtain a flat list with all nodes with specific attribute values, Linq provides an elegant solution.
Solution
To flatten the tree in a Linq query and screen the specific attribute value, please follow the steps below:
The following is a detailed explanation:
<code class="language-csharp">// 扁平化树 IEnumerable<mynode> flatTree = e.SelectMany(c => Flatten(c.Elements)).Concat(new[] { e }); // 按属性值筛选扁平化列表 var result = flatTree.Where(n => n.group == 1);</code>
The generic version of the custom tree
For trees that are different from "MyNode", you can use the generic version of the flat function. This version uses a function to retrieve the node:
<code class="language-csharp">public static IEnumerable<mynode> Flatten(this IEnumerable<mynode> e) => e.SelectMany(c => c.Elements.Flatten()).Concat(e);</code>
To flatten the "MyNode" tree and screen the node of "group" equal to 1:
By understanding the flat concept of tree and the strong operation of Linq, you can efficiently extract and operate data from the complex hierarchical structure.
<code class="language-csharp">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>
The above is the detailed content of How Can LINQ Efficiently Flatten Hierarchical Data and Filter by a Specific Property Value?. For more information, please follow other related articles on the PHP Chinese website!