Linq, join, group, count;选择更多的值

本文关键字:选择 join group count Linq | 更新日期: 2023-09-27 18:04:53

使用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 = ..,  
    }

有人知道怎么做吗?

谢谢你的帮助!

Linq, join, group, count;选择更多的值

所以你确定所有具有相同CompanyNameSupplier组都保证具有相同的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 
}

EDIT

嗯…除非我弄错了,否则这可以做得更干净:

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将按键值分组,而不是整个实体。