i have a data table and now i want to convert it into collection so how i convert data table to collection?
Thanks
Shailendra
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Nayeem MansooriPosted Apr 27, 2013, 3:18 AM
the following is the method through which you can convert any list object to datatable..
public DataTable ConvertToDataTable
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties) row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; table.Rows.Add(row);
}
return table;
}
Sam HobbsPosted Sep 27, 2010, 5:56 PM
Suthish NairPosted Sep 27, 2010, 7:47 AM
Another simple way..
using System.Collections.Generic;
DataSet ds = new DataSet(); //for example
List
2.
List
foreach (DataRow item in ds.Tables[0].Rows)
{
list.Add(item);
}
Manikavelu VelayuthamPosted Sep 27, 2010, 7:19 AM
One of the optimized way of doing this is through LINQ.
Below code will help you.
List<MyObject> NewList= new List<MyObject>();
DataTable dtMyData = new MyTableAdapter().GetMyData();
NewList= (from l in dtMyData
select new MyObject
{
Active = l.IsActive,
Email = l.Email,
ZipCode = l.Zipcode
}).ToList();