简体   繁体   English

Linq to Sql,由2个属性和子串组成

[英]Linq to Sql, group by 2 property and substring

I have an initial query that I want to modify to increase granularity in my results. 我有一个初始查询,我想修改以增加结果的粒度。 But Visual Studio tells me my query isn't valid and I can't understand why. 但Visual Studio告诉我我的查询无效,我无法理解为什么。 Basically I want to group my data according to 2 property (columns) and also group one of the property by the first N characters. 基本上我想根据2个属性(列)对数据进行分组,并且还按前N个字符对属性中的一个进行分组。

Initial query that works: 有效的初始查询:

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;

Query marked by ** as wrong by VS2010: 由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;

The new { } object syntax requires that properties have names - something your original query did not require. 新的{}对象语法要求属性具有名称 - 这是您的原始查询不需要的名称。 It cannot infer a name from your method call. 它无法从方法调用中推断出名称。 So I'd recommend changing it to something like: 所以我建议将其更改为:

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() 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM