从Linq中的数据表中选择不同的行

B V*_*hya 3 c# 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();
Run Code Online (Sandbox Code Playgroud)

任何建议都有帮助.

Gil*_*een 5

这段代码返回的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();
Run Code Online (Sandbox Code Playgroud)

您也可以这样加入这两个查询:

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();
Run Code Online (Sandbox Code Playgroud)