2013-06-05 129 views
1

我有一个初始查询,我想要修改,以增加我的结果中的粒度。但Visual Studio告诉我,我的查询是无效的,我不明白为什么。基本上我想根据2个属性(列)对数据进行分组,并按照前N个字符对其中一个属性进行分组。Linq到Sql,由2属性和子字符串组

,工程初始查询:

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; 

查询被标记为**错了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; 

回答

3

新{}对象语法要求性能有名字 - 这是你原来的查询做不需要。它不能从您的方法调用中推断出一个名称。所以我建议将其改为如下:

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

确实,这个工作。我现在的问题是,为什么第二个属性不需要名称? – guiomie

+1

编译器能够推断出该名称,因为它只是一个属性,而不是方法调用。如果你想到它,编译器只能看到在第一种情况下发生的“最后一件事” - 它只是看到一个“调用的子字符串方法返回一个字符串” - 它看不到什么属性的子字符串被调用。 –