分组而不重复供应商行

时间:2015-06-22 23:30:58

标签: c# .net linq linq-to-sql

从3个表中使用Linq-to-SQL从NorthWind获取数据时遇到问题:

  1. Suppliers
  2. Products
  3. Categories
  4. 我想获取categoryId > 3类别中所有产品的供应商。结果集需要每个供应商1行,然后一些子集包含每个产品的行,包括类别信息。这个想法是这个结果集将作为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中,结果集看起来像包含许多重复的供应商。 有什么想法吗?

    EDITED: 感谢Adduci的回答,我最终得到了以下有效的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
                     }  
    }
    

    额外by new { sups.SupplierID, sups.CompanyName }完成结果集,包括供应商字段。尼斯!

2 个答案:

答案 0 :(得分:2)

第一步是使用匿名类

将3个表组合在一起
group new { sups, prods, cats } 

您应该明确定义您想要的属性,而不是select gIGrouping<...>):

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
                 }  
}

这样可以防止从数据库中返回未使用的信息

答案 1 :(得分:1)

加入表格时经常出现这种情况。您通常可以使用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()