Just Code‎ > ‎

C# - Convert List to DataTable

posted Feb 4, 2010, 3:02 PM by Peter Henell
Original post:
http://derekreynolds.wordpress.com/2010/02/03/convert-list-to-datatable-listtodatatable-function/

using
System.Data; using System.Reflection; private static DataTable ListToDataTable<T>(List<T> list) { DataTable dt = new DataTable(); foreach (PropertyInfo info in typeof(T).GetProperties()) { dt.Columns.Add(new DataColumn(info.Name, info.PropertyType)); } foreach (T t in list) { DataRow row = dt.NewRow(); foreach (PropertyInfo info in typeof(T).GetProperties()) { row[info.Name] = info.GetValue(t, null); } dt.Rows.Add(row); } return dt; }
Comments