How to convert DataTable to Generic List using LINQ in C#?

Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 971
Let us create a datatable as under

private DataTable MyDataTable()
DataTable dtsource = new DataTable("Details");

//Adding columns to datatable
dtsource.Columns.Add("Gender", typeof(bool));

//Adding records to the datatable
dtsource.Rows.Add("Name1", 1);
dtsource.Rows.Add("Name2", 1);
dtsource.Rows.Add("Name3", 0);
dtsource.Rows.Add("Name4", 1);
dtsource.Rows.Add("Name5", 0);

return dtsource;

Then fire the below query

var dt = (from dr in MyDataTable().AsEnumerable()
select new
Name = dr.Field<string>("Name"),
Category = dr.Field<bool>("Gender"),
NewCategory = dr.Field<bool>("Gender") ? "Male" : "Female"

We are using the AsEnumerable() extension method which is available in System.Data.DataSetExtensions assembly.

Comments or Responses

Login to post response