C# Linq到Sql,按2属性和子字符串分组
我有一个初始查询,我想修改它以增加结果的粒度。但是VisualStudio告诉我我的查询无效,我不明白为什么。基本上,我希望根据2个属性(列)对数据进行分组,并根据前N个字符对其中一个属性进行分组 有效的初始查询:C# Linq到Sql,按2属性和子字符串分组,c#,.net,linq,linq-to-sql,C#,.net,Linq,Linq To Sql,我有一个初始查询,我想修改它以增加结果的粒度。但是VisualStudio告诉我我的查询无效,我不明白为什么。基本上,我希望根据2个属性(列)对数据进行分组,并根据前N个字符对其中一个属性进行分组 有效的初始查询: List<PostalCode> codes = (from customer in bd.Customers group customer by customer.postalcode.Substring(0, posta
List<PostalCode> codes = (from customer in bd.Customers
group customer by customer.postalcode.Substring(0, postalCodeLength) into postalCodes
select new PostalCode
{
Postal = postalCodes.Key,
Count = postalCodes.Count()
}).ToList();
return codes;
列出代码=(来自bd.Customers中的customer
按customer.postalcode.Substring(0,postalCodeLength)将customer分组为postalCodes
选择新的邮政编码
{
Postal=postalCodes.Key,
Count=postalCodes.Count()
}).ToList();
返回码;
VS2010将**标记为错误的查询:
List<PostalCode> codes = (from customer in bd.Customers
group customer by new { **customer.postalcode.Substring(0, postalCodeLength)**, customer.CustomerGroupType}
into postalCodes
select new PostalCode
{
Postal = postalCodes.Key.postalcode,
CustomerGroupType = postalCodes.Key.CustomerGroupType,
Count = postalCodes.Count()
}).ToList();
return codes;
列出代码=(来自bd.Customers中的customer
按新的{**customer.postalcode.Substring(0,postalCodeLength)**,customer.CustomerGroupType}对客户进行分组
成为邮递员
选择新的邮政编码
{
Postal=postalCodes.Key.postalcode,
CustomerGroupType=postalCodes.Key.CustomerGroupType,
Count=postalCodes.Count()
}).ToList();
返回码;
新的{}对象语法要求属性具有名称,这是原始查询不需要的。它无法从方法调用中推断名称。因此,我建议将其改为:
from customer in bd.Customers
group customer by new { TrimmedPostalCode = customer.postalcode.Substring(0, postalCodeLength), customer.CustomerGroupType}
into postalCodes
select new PostalCode
{
Postal = postalCodes.Key.TrimmedPostalCode,
CustomerGroupType = postalCodes.Key.CustomerGroupType,
Count = postalCodes.Count()
}
事实上,这起了作用。我现在要问的问题是,为什么第二个属性不需要名称?编译器能够推断名称,因为它只是一个属性,而不是一个方法调用。仔细想想,编译器只能看到第一种情况下发生的“最后一件事”——它只看到“调用了返回字符串的Substring方法”——它看不到调用了什么属性Substring。