How to return both parent and child using LINQ against 1 table

前端 未结 7 727
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 17:10

Been looking for a solution for this but haven\'t been able to find one so far.

I\'m fairly sure its possible with one linq call but having trouble working it out.

7条回答
  •  时光说笑
    2021-01-19 18:04

    for your sample data, this will work :

            var validData = from d in data
                            where (!d.ParentID.HasValue && d.IsValid) //select all valid parents
                            || (d.ParentID.HasValue && data.Where(p => !p.ParentID.HasValue && p.IsValid).Select(p => p.ID).Contains(d.ParentID.Value)) //select children
                            select d;
    

    but it won't work if there are multi-level hierarchies in your data, and you want to select the sub-children too.

    another thing, i'm not sure if the above will work on linq-to-sql or another linq provider, but it does work for in-memory data.

提交回复
热议问题