Hierarchy Problem & # 8594; Replace recursion with Linq Join?

I have my own reference table that has an ID, ParentID (with NULL capability).

Thus, the table contains many nodes, each of which node can be a root in the hierarchy (the parent element is null) or at any hierarchy level (the parent exists elsewhere in the table).

Given the arbitrary launch of a node, is there an elegant linq query that will return all children of the hierarchy from that node?

Thanks.

+3
source share
4 answers

If you want to select all direct children of a node, the following query must complete the following task:

from item in table
where item.ID == parentID;
select item

node, LINQ, , LINQ ( SQL) . p >

. :

+3

, :

class MyTable
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public MyTable(int id, int? parentId) { this.Id = id; this.ParentId = parentId; }
}

List<MyTable> allTables = new List<MyTable> {
    new MyTable(0, null), 
    new MyTable(1, 0),
    new MyTable(2, 1)
};

Func<int, IEnumerable<MyTable>> f = null;
f = (id) =>
{
    IEnumerable<MyTable> table = allTables.Where(t => t.Id == id);

    if (allTables
        .Where(t => t.ParentId.HasValue && t.ParentId.Value == table
            .First().Id).Count() != 0)
        return table
            .Union(f(
            allTables.Where(t => t.ParentId.HasValue && t.ParentId.Value == table
                .First().Id).First().Id));
    else return table;

};

, SQL ALL ALL.

+3

Basically, I am going with something like this, as described in the SO link you created.

public IQueryable GetCategories(Category parent)
{
    var cats = (parent.Categories);
    foreach (Category c in cats )
    {
        cats  = cats .Concat(GetCategories(c));
    }
    return a;
}

CTE is probably the best solution, but now I want to keep everything on the same level.

0
source

Source: https://habr.com/ru/post/1717876/


All Articles