LINQ:结合加入和分组依据 [英] LINQ: combining join and group by
问题描述
我有一个结合了连接和组的查询,但我遇到了问题.查询如下:
I have a query that combines a join and a group, but I have a problem. The query is like:
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
.
As you see, it joins the Products
table with the BaseProducts
table, and groups on an id of the Product
table. But in the resulting ProductPriceMinMax
, I also need a property of the BaseProducts
table: bp.Name
, but it doesn't know bp
.
知道我做错了什么吗?
推荐答案
完成此操作后
group p by p.SomeId into pg
您不再可以访问初始 from
中使用的范围变量.也就是不能再讲p
或bp
,只能讲pg
.
you no longer have access to the range variables used in the initial from
. That is, you can no longer talk about p
or bp
, you can only talk about pg
.
现在,pg
是一个组,因此包含多个产品.给定 pg
组中的所有产品都具有相同的 SomeId
(因为这是您分组的内容),但我不知道这是否意味着它们都具有相同的 <代码>BaseProductId.
Now, pg
is a group and so contains more than one product. All the products in a given pg
group have the same SomeId
(since that's what you grouped by), but I don't know if that means they all have the same BaseProductId
.
要获得基本产品名称,您必须在 pg
组中选择一个特定的产品(就像您使用 SomeId
和 CountryCode
>),然后然后加入BaseProducts
.
To get a base product name, you have to pick a particular product in the pg
group (As you are doing with SomeId
and CountryCode
), and then join to 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
};
也就是说,这看起来很不寻常,我认为您应该退后一步,考虑一下您实际尝试检索的内容.
That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.
这篇关于LINQ:结合加入和分组依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!