B Vidhya
B Vidhya

Reputation: 339

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.

Upvotes: 4

Views: 6562

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

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

Upvotes: 5

Related Questions