C# 将数据库查询结果分组到嵌套泛型列表中

本文关键字:嵌套 泛型 列表 数据库 查询 结果 | 更新日期: 2023-09-27 17:56:40

我正在从存储过程中获取查询数据,我需要将其分组为 3 个泛型列表。我不知道如何做到这一点。

以下是数据查询结果的摘要:

Child   |   Parent  |   GrandChildren
a2      |   a1      |   a30
a2      |   a1      |   a31
a2      |   a1      |   a32
b2      |   b1      |   b30
b2      |   b1      |   b31
c2      |   c1      |   c30
d2      |   d1      |   d30
d2      |   d1      |   d31
d3      |   d1      |   d32
d3      |   d1      |   d33

以下是我想对数据进行分组的方式。

public class Parent
{
    public int ID { get; set; }
    public string Name  { get; set; }
    public List<Child> Children { get; set; }
}
public class Child
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<GrandChild> GrandChildren { get; set; }
}
public class GrandChild
{
    // numerous properties.
}

这是我尝试过的,但没有运气。

var data = Repository.GetData();
var groupedData = from d in data
                    where d.Parent > 0
                    group d by d.Parent into ParentGroup
                    select parentGroup.ToList();
// Result: Grouped list of "Parent", not with grouped "Child" and grouped "GrandChildren" as per desired structure above.

C# 将数据库查询结果分组到嵌套泛型列表中

你也必须对孙子孙女进行分组。像这样:

var data = Repository.GetData();
// Group the Grandchildren first
var grandkids = from d in data
                where d.Child > 0
                group d by d.Child into GrandChildGroup
                select new Grandchild {
                    // Assign grand child properties here
                };
// Group the Children
var children = from d in data
               where d.Parent > 0
               group d by d.Parent into ChildGroup
               select new Child {
                   // Assign child properties here
                   Grandchildren = ( from gc in grandkids
                                     where gc.Parent = d.Child
                                     select gc ).ToList()
               };
// Now group the parents
var groupedData = from p in data
                  select new Parent {
                      // Assign parent properties here
                      Children = ( from kid in children
                                   where kid.Parent = p.Parent
                                   select kid ).ToList()
                  }.ToList();