简体   繁体   中英

Selecting distinct rows from datatable in Linq

I'm using linq query to select 2 distinct columns id and name from a datatable. 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> . Add a ToList() after the 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM