I have data from database like that :
id | description | parent_id
-----------------------------------------
1 | Record 1 | null
2 | Record 2 | 1
3 | Record 3 | null
4 | Record 4 | 2
5 | Record 5 | 3
I want to process using Linq, and it should be result like this :
Record 1
- Record 2
- Record 4
Record 3
- Record 5
I got solution : Recursive LINQ query: select item and all children with subchildren
but unfortunately the result only has two level, because i want the result in multi level > 2 levels (like a tree).
Any other best solution ? or how to modification that solution
Thanks in advance
For linq-to-objects you can define your own extension method on IEnumerable<T>
that recursively gets all children.
public static class EnumerableExtensions
{
public static IEnumerable<T> SelectRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
foreach (var parent in source)
{
yield return parent;
var children = selector(parent);
foreach (var child in SelectRecursive(children, selector))
yield return child;
}
}
}
Usage:
var lookup = col.ToLookup(x => x.Parent_Id);
var res = lookup[null].SelectRecursive(x => lookup[x.Id]).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With