Linq,加入,小组,计数>选择更多值

时间:2011-08-09 23:15:55

标签: c# linq

使用LINQ我正在执行以下操作来选择供应商及其产品数量:

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by s.CompanyName 
into result 
select new {   
    SupplierName = result.Key,   
    ProductCount = result.Count() 
}

这很好用,但我想从供应商表,SupplierId和SupplierAddress中选择更多属性,例如:

....    
select new {   
    SupplierName = result.Key,   
    ProductCount = result.Count(),   
    SupplierId = ..,   
    SupplierAddress = ..,  
    }

有谁知道怎么做?

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

因此,您确定具有相同Supplier的所有CompanyName个群组都保证拥有相同的IdAddress

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by s.CompanyName 
into result 
select new {   
    SupplierName = result.Key,   
    ProductCount = result.Count(),
    SupplierId = result.First().Id,
    SuppliedAddress = result.First().Address 
}

如果您按Id分组,或者可能全部分组,则会更自然:

from s in context.Suppliers 
join p in context.Products on s equals p.Supplier 
group s by new { s.CompanyName, s.Id, s.Address } 
into result 
select new {   
    ProductCount = result.Count(),
    SupplierName = result.Key.CompanyName,   
    SupplierId = result.Key.Id,
    SuppliedAddress = result.Key.Address 
}

答案 1 :(得分:1)

修改

嗯......除非我弄错了,否则可以更清洁地完成:

context
    .Products
    .GroupBy(p=>p.Supplier)
    .Select(result=>new {
        SupplierName = result.Key,   
        ProductCount = result.Count(),
        SupplierId = result.Key.Id,   
        SupplierAddress = result.Key.Address,  
    }

联接是从数据库中的FK关系开箱即用的,因此Product已经有Supplier。您似乎在自己的代码(...equals p.Supplier)中发现了此设置,然后无法理解其含义。抱歉从理解语法转变为方法链。他们对我来说更自然。

补充@ Dan的评论(对于Linq2Objects来说可能是正确的),在Linq2Sql中(我不能担保L2E,但我想它大致相同),如果你按照FK关系生成的属性进行分组,生成的SQL将产生GROUP BY键值,而不是整个实体。