B Vidhya B Vidhya - 3 months ago 12
C# Question

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.

Answer

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