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

前端 未结 7 787
隐瞒了意图╮
隐瞒了意图╮ 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 17:48

    If you're using Entity Framework and have Navigation Properties, you could do the following. It's not clear from the question whether this is the case though.

    var query = db.YourTable
        .Where(x => x.Parent != null && x.Parent.ValidFlag == 1)
        .GroupBy(x => x.ParentId)
        .Select(g => new { ParentId = g.Key, Children = g.ToList() })
        .ToList();
    

提交回复
热议问题