LINQ group by query help: Select another related table with key
LINQ group by query help: Select another related table with key
请帮我完成以下查询:
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。我想在 above/main 单个查询中得到每个 Group
以及加入它的 cats
的列表,理想情况下无需在单独的查询中再次重新查询该数据.
非常感谢
我不确定我是否理解正确,但我认为这就是您所需要的:代替 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)}
请帮我完成以下查询:
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。我想在 above/main 单个查询中得到每个 Group
以及加入它的 cats
的列表,理想情况下无需在单独的查询中再次重新查询该数据.
非常感谢
我不确定我是否理解正确,但我认为这就是您所需要的:代替 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)}