Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq recursive parent child

Tags:

c#

recursion

linq

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

like image 219
FirmanHidayat Avatar asked Jan 12 '17 08:01

FirmanHidayat


1 Answers

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();
like image 83
Magnus Avatar answered Oct 23 '22 01:10

Magnus