2013-04-24 86 views
0

我有2個屬性具有相同的名稱:給予一個別名匿名類型屬性不工作

List<CustomerWithCountry> customersList = CustomerEntity.LoadCustomersSubsetForCriteria(null, 0, 100, null) 
.Select(c => new { c.CODE, c.NAME, c.COUNTRY.NAME }).ToList(); 

它有c.Name和c.Country.Name具有相同名稱的問題。

所以我試着給c.Country.Name一個別名:

.Select(c => new { c.CODE, c.NAME, CountryName = c.COUNTRY.NAME }).ToList(); 

給了我以下錯誤:

Error 3 Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#3>' to 'System.Collections.Generic.List<ViewCustomersPage.CustomerWithCountry>'

回答

4

該錯誤應該是不存在的別名爲好,因爲您正在選擇Anonymous type,並且您試圖將ToList的結果分配給List<CustomerWithCountry>。你需要將結果投影到你的課CustomerWithCountry

因此,在您的查詢應該是:

select (c=> new CustomerWithCountry() {..... 

但要記住,如果你的類是從實體框架或LINQ來SQL則無法投射到該類型。

+1

算了:) 感謝 – AngelicCore 2013-04-24 10:32:35

+0

@AngelicCore,歡迎您 – Habib 2013-04-24 11:46:40

2

創建新CustomerWithCountry對象

List<CustomerWithCountry> customersList = 
      CustomerEntity.LoadCustomersSubsetForCriteria(null, 0, 100, null) 
       .Select(c => new CustomerWithCountry{ 
         CODE= c.CODE, 
         NAME= c.NAME, 
         CountryName = c.COUNTRY.NAME }) 
       .ToList();