Linq to Sql,按2属性和子字符串分组
本文关键字:字符串 属性 to Sql Linq | 更新日期: 2023-09-27 18:17:00
我有一个初始查询,我想修改它以增加结果的粒度。但是Visual Studio告诉我,我的查询是无效的,我不明白为什么。基本上,我想根据2属性(列)分组我的数据,并通过前N个字符分组属性之一。
有效的初始查询:
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;
用**标记的查询是错误的:
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;
新的{}对象语法要求属性有名称——这是您最初的查询所不需要的。它不能从方法调用中推断出名称。所以我建议把它改成:
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()
}