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

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


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

//Adding columns to datatable
dtsource.Columns.Add("Name",typeof(string));
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 = MyDataTable().AsEnumerable()
.Select(dr => new {
Name = dr.Field<string>("Name"),
Category = dr.Field<bool>("Gender"),
NewCategory = dr.Field<bool>("Gender") ? "Male" : "Female"
}).ToList();


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

Comments or Responses

Login to post response