请帮我完成以下查询:
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>
非常感谢
答案 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)}