C# LINQ group by Dons';行不通
我有一个LINQ查询:C# LINQ group by Dons';行不通,c#,linq,C#,Linq,我有一个LINQ查询: from p in Products join c in Categories on p.CategoryID equals c.CategoryID group p by p.Category into prices select new {price = prices.Average(p => p.UnitPrice), name = p.Category.CategoryName } 我得到的错误是: The name 'p' does not exist
from p in Products
join c in Categories on p.CategoryID equals c.CategoryID
group p by p.Category into prices
select new {price = prices.Average(p => p.UnitPrice), name = p.Category.CategoryName }
我得到的错误是:
The name 'p' does not exist in the current context
为什么我不能在这里访问p?如何解决此问题?您可以使用
键
:
...
group p by p.Category into prices
select new
{
price = prices.Average(p => p.UnitPrice),
name = prices.Key.CategoryName
}
谢谢知道我为什么要在这里用钥匙吗?@Bv202:因为你不能在这里访问
p
,所以它超出了范围。您可以访问产品组(可以包含多个产品)。类别
是组的键,因此您可以使用键
属性。