我有一个结合了联接和组的查询,但我遇到了问题。查询如下:
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
中使用的范围变量。也就是说,你不能再谈论p
或bp
,你只能谈论pg
。
现在,pg
是一个组,因此包含多个 产品。给定 pg
组中的所有产品都具有相同的 SomeId
(因为这是您分组的依据),但我不知道这是否意味着它们都具有相同的 BaseProductId
.
要获得基本产品名称,您必须在 pg
组中选择一个特定产品(就像您使用 SomeId
和 CountryCode
),然后然后加入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/