Wednesday, May 11, 2011

Convert IEnumerable to DataTable

Here is small example to convert IEnumerable to DataTable by using the keyword CopyToDataTable()

DataTable dt = new DataTable();

//Adding Columns and names
dt.Columns.Add("ID" ,typeof(int));
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Rank",typeof(string));

//Adding Rows and values

dt.Rows.Add(1,"anish","First");
dt.Rows.Add(2,"marokey","First");
dt.Rows.Add(2,"varghese","Second");

//querying the result where ID is 2
IEnumerable result = from p in dt.AsEnumerable()
where p.Field("ID") == 2
select p;

// By using the keyword CopyToDataTable(.net 3.5 SP1 and above) converting the IEnumerable to DataTable
DataTable dtConvertedFromLinq = result.CopyToDataTable();

No comments:

Post a Comment