LINQ group by query help:用key选择另一个相关表

时间:2016-08-23 22:39:52

标签: c# linq linq-to-sql

请帮我完成以下查询:

var results = from species in db.Species
              join cats in db.Categories on species.CategoryId equals cats.CategoryId
              join groups in db.Groups on cats.GroupId equals groups.GroupId
              group groups by groups into g
              select new GroupWithCategoryChildren
              {
                  Group = g.Key,
                  Categories = (cats from above query for this same g.Key group)???
              };

我可以用SQL轻松地做到这一点,但我正在努力使用LINQ。我希望最终得到每个Group ALONG与在上面/主要单个查询中加入它的cats的列表,理想情况下不会在单独的查询中再次重新查询该数据。< / p>

非常感谢

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解正确,但我认为这就是您所需要的:而不是group groups by groups执行group cats by groups,然后Key将成为groups并且该组的值将是所有匹配的类别。

var results = from species in db.Species
              join cats in db.Categories on species.CategoryId equals cats.CategoryId
              join groups in db.Groups on cats.GroupId equals groups.GroupId
              group cats by groups into g
              select new GroupWithCategoryChildren
              {
                  Group = g.Key,
                  Categories = g.ToList()
              };

我用它来测试它:

List<dynamic> Species = new List<dynamic>()
{
    new { A = "1", CategoryId = 1 },
    new { A = "2", CategoryId = 2 },
};

List<dynamic> Categories = new List<dynamic>
{
    new { B = "1", CategoryId = 1, GroupId = 1 },
    new { B = "2", CategoryId = 2, GroupId = 1 },
};

List<dynamic> Groups = new List<dynamic>
{
    new { C = "1", GroupId = 1 }
};

//result: { Group: { C = "1", GroupId = 1 }, Categories (1,2)}