c# - LINQ:结合加入和分组依据

标签 c# linq linq-to-sql join group-by

我有一个结合了联接和组的查询,但我遇到了问题。查询如下:

 var result = from p in Products                         
 join bp in BaseProducts on p.BaseProductId equals bp.Id                    
 group p by p.SomeId into pg                         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  <------ can't use bp. 
 };

如您所见,它将 Products 表与 BaseProducts 表连接起来,并根据 Product 表的 id 进行分组。但是在生成的 ProductPriceMinMax 中,我还需要 BaseProducts 表的一个属性:bp.Name,但它不知道 bp.

知道我做错了什么吗?

最佳答案

完成后

group p by p.SomeId into pg  

您不再有权访问初始 from 中使用的范围变量。也就是说,你不能再谈论pbp,你只能谈论pg

现在,pg 是一个,因此包含多个 产品。给定 pg 组中的所有产品都具有相同的 SomeId(因为这是您分组的依据),但我不知道这是否意味着它们都具有相同的 BaseProductId.

要获得基本产品名称,您必须在 pg 组中选择一个特定产品(就像您使用 SomeIdCountryCode),然后然后加入BaseProducts

var result = from p in Products                         
 group p by p.SomeId into pg                         
 // join *after* group
 join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  // now there is a 'bp' in scope
 };

也就是说,这看起来很不寻常,我认为您应该退后一步,考虑一下您实际要检索的内容。

关于c# - LINQ:结合加入和分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9173410/

相关文章:

c# - LINQ-SQL 在单个事务中更新多行

asp.net - 将选定值设置为 UserControl 中的 DropDownList

c# - 通用列表替换

.net - 通过 LINQ 选择十进制值

c# - 在 Javascript 中绑定(bind) Radscheduler

c# - 从 IEnumerable<T> 到 IEnumerable<Quantity<T>> 中选择

c# - 如何从表记录中选择除某些列外的记录

c# - 使用 LINQ to SQL 的 .NET 架构的最佳设计实践(需要 DAL?我们真的可以使用 POCO 吗?要采用的设计模式?)

c# - 自定义集合无法实现 IEnumerable<T>

c# - .net 4 的线程转储