简体   繁体   English

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

[英]Selecting distinct rows from datatable in Linq

I'm using linq query to select 2 distinct columns id and name from a datatable. 我正在使用linq查询从数据表中选择2个不同的列id和name。 I've the code below but it's throwing error specific cast is invalid. 我有下面的代码,但它抛出错误特定的强制转换是无效的。

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

Any suggestions could help. 任何建议都有帮助。

This code returns an IEnumerble<T> while the DataSource is probably expecting a List<T> . 此代码返回IEnumerble<T>DataSource可能需要List<T> Add a ToList() after the Distinct() : Distinct()之后添加一个ToList() Distinct()

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

You can also just join the two queries this way: 您也可以这样加入这两个查询:

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