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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Manikavelu VelayuthamRank #413 · 6K reputationPosted Sep 27, 2010, 3:19 AM EDT
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();
Suthish NairRank #92 · 22.8K reputationPosted Sep 27, 2010, 3:47 AM EDT
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);
}
Sam HobbsRank #107 · 20.5K reputationPosted Sep 27, 2010, 1:56 PM EDT
Nayeem MansooriRank #3,979 · 374 reputationPosted Apr 26, 2013, 11:18 PM EDT
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;
}