簡體   English   中英

從Linq中的數據表中選擇不同的行

[英]Selecting distinct rows from datatable in Linq

我正在使用linq查詢從數據表中選擇2個不同的列id和name。 我有下面的代碼,但它拋出錯誤特定的強制轉換是無效的。

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

任何建議都有幫助。

此代碼返回IEnumerble<T>DataSource可能需要List<T> Distinct()之后添加一個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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM