2016-09-01 75 views
2

我正在使用linq查詢從數據表中選擇2個不同的列id和名稱。我有下面的代碼,但它是拋出錯誤特定的演員是無效的。從Linq中的數據表中選擇不同的行

sdatatable = ds.Tables[0].AsEnumerable().Where(x => x.Field<string>  
      ("TableName") == "header").CopyToDataTable(); 

rptcourse.DataSource = sdatatable.AsEnumerable().Select(row => new 
     { 
      locationid = row.Field<string>("locationID"), 
      locationname = row.Field<string>("locationname") 
     }).Distinct(); 

任何建議可以幫助。

+0

是什麼sdatatable的類型? –

+0

這是一個數據表。 –

+0

請顯示*確切*例外信息。如果我們沒有看到那裏的類型,我們無法幫助你。 –

回答

4

此代碼返回IEnumerble<T>,而DataSource可能期望List<T>。添加ToList()Distinct()

rptcourse.DataSource = sdatatable.AsEnumerable().Select(row => new 
     { 
      locationid = Convert.ToInt32(row["locationid"]), 
      locationname = row.Field<string>("locationname") 
     }).Distinct().ToList(); 

你也可以加入這兩個查詢是這樣的:

rptcourse.DataSource = ds.Tables[0].Where(x => x.Field<string>("TableName") == "header") 
      .Select(row => new 
      { 
       locationid = Convert.ToInt32(row["locationid"]) 
       locationname = row.Field<string>("locationname") 
      }) 
      .Distinct().ToList(); 
+0

我嘗試了兩種解決方案,但仍然得到相同的錯誤。 –

+0

@BVidhya - 你在什麼時候得到例外?它說什麼 - 哪個是無效的演員? –

+0

在屬性locationid和locationname上拋出錯誤特定的轉換無效。我將locationid字段類型更改爲int。但仍然會拋出錯誤 –

相關問題