2013-06-05 178 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

編譯器能夠推斷出該名稱,因爲它只是一個屬性,而不是方法調用。如果你想到它,編譯器只能看到在第一種情況下發生的「最後一件事」 - 它只是看到一個「調用的子字符串方法返回一個字符串」 - 它看不到什麼屬性的子字符串被調用。 –