C# 分组而不复制供应商行
从3个表中使用Linq to SQL从NorthWind获取数据时遇到问题:C# 分组而不复制供应商行,c#,.net,linq,linq-to-sql,C#,.net,Linq,Linq To Sql,从3个表中使用Linq to SQL从NorthWind获取数据时遇到问题: 供应商 产品 类别 我想找到类别ID>3的所有产品的供应商。结果集需要每个供应商一行,然后一些子集包含每个产品一行,包括类别信息。其思想是,此结果集将作为ajax调用的json值返回 以下是我迄今为止所做努力的最简单版本: from sups in Suppliers join prods in Products on sups.SupplierID equals prods.SupplierID join cats
供应商
产品
类别
类别ID>3
的所有产品的供应商。结果集需要每个供应商一行,然后一些子集包含每个产品一行,包括类别信息。其思想是,此结果集将作为ajax调用的json值返回
以下是我迄今为止所做努力的最简单版本:
from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where ( cats.CategoryID > 3)
group sups by sups.SupplierID into g
select g
在LinqPad中,结果集似乎包含许多重复的供应商。
有什么想法吗
编辑:
多亏了艾加诺西的回答,我最终得出了以下LINQ工作声明:
from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where cats.CategoryID > 3
group new { sups, prods, cats } by new { sups.SupplierID, sups.CompanyName } into g
select new
{
g.Key,
ProductInfo = from x in g
select new
{
ProductProperty = x.prods.ProductName,
CategoryProperty = x.cats.CategoryName
}
}
新的{sups.SupplierID,sups.CompanyName}额外的
完成包括供应商字段的结果集。很好 在连接表时通常会出现这种情况。您通常可以使用Distinct()
来修复此问题
大概是这样的:
(from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where ( cats.CategoryID > 3)
group sups by sups.SupplierID into g
select g).Distinct()
from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where cats.CategoryID > 3
group new { sups, prods, cats } by sups.SupplierID into g
select new
{
Supplier = g.Key,
ProductInfo = from x in g
select new
{
ProductProperty = x.prods.Prop1,
CategoryProperty = x.cats.Prop1
}
}
第一步是使用匿名类将3个表分组在一起
group new { sups, prods, cats }
与其选择g(一种(i分组)
),不如明确定义所需的属性,如下所示:
(from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where ( cats.CategoryID > 3)
group sups by sups.SupplierID into g
select g).Distinct()
from sups in Suppliers
join prods in Products on sups.SupplierID equals prods.SupplierID
join cats in Categories on prods.CategoryID equals cats.CategoryID
where cats.CategoryID > 3
group new { sups, prods, cats } by sups.SupplierID into g
select new
{
Supplier = g.Key,
ProductInfo = from x in g
select new
{
ProductProperty = x.prods.Prop1,
CategoryProperty = x.cats.Prop1
}
}
这样可以防止从数据库返回未使用的信息我看到您已将g.prods的打字错误修复为x.prods。谢谢!!工作完美!我刚刚意识到,这还有一个问题:供应商记录信息本身只包含键值和productinfo。。。这可以扩展到其他供应商财产(ex CompanyName?)@Paul0515-是的。您可以添加CompanyName=g.FirstOrDefault().sups.CompanyName
,或者您的方式可能会更好。感谢您的建议,其中一个问题是在同一行上获取产品和类别的属性。。。