The method below converts an array of objects to a DataTable object in C#.
public static DataTable GetDataTableFromObjects(object[] objects)
{
if (objects != null && objects.Length > 0)
{
Type t = objects[0].GetType();
DataTable dt = new DataTable(t.Name);
foreach (PropertyInfo pi in t.GetProperties())
{
dt.Columns.Add(new DataColumn(pi.Name));
}

michael gillsonPosted Nov 17, 2008, 1:29 PM
Code should allow a DataTable to be returned even if the object array length is zero. Using Generics allows this. As the number of objects in the lists becomes large, using GetType().GetProperty inside the foreach loops is slow. I did not show how to fix this performance problem but a simple mapping outside of the loops only needs to be done once. The generic constraint,where TDataClass : class<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p>, means every item in the list must be an object or derives from type object. public static DataTable GetDataTableFromObjects<TDataClass>(List<TDataClass> dataList)<o:p></o:p> where TDataClass : class<o:p></o:p> {<o:p></o:p> Type t = typeof(TDataClass);<o:p></o:p> DataTable dt = new DataTable(t.Name);<o:p></o:p> foreach (PropertyInfo pi in t.GetProperties())<o:p></o:p> {<o:p></o:p> dt.Columns.Add(new DataColumn(pi.Name));<o:p></o:p> }<o:p></o:p> if (dataList != null)<o:p></o:p> {<o:p></o:p> foreach (TDataClass item in dataList)<o:p></o:p> {<o:p></o:p> DataRow dr = dt.NewRow();<o:p></o:p> foreach (DataColumn dc in dt.Columns)<o:p></o:p> {<o:p></o:p> dr[dc.ColumnName] = <o:p></o:p> item.GetType().GetProperty(dc.ColumnName).GetValue(item, null);<o:p></o:p> }<o:p></o:p> dt.Rows.Add(dr);<o:p></o:p> }<o:p></o:p> }<o:p></o:p> return dt;<o:p></o:p> }<o:p></o:p>
Mahesh ChandPosted Sep 29, 2008, 3:06 PM
You can format the code by copying your code from Visual Studio to Microsoft word and then copy from word to this online editor.
Gangadhar AddagatlaPosted Sep 29, 2008, 9:54 AM
Dynamic Objects Conveting into Data Table in C#