1 public class ListToDatatable 2 { 3 public static DataTable ToDataTable <T> (List <T> items) 4 { 5 var tb = new DataTable(typeof(T).Name); 6 7 PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 8 9 foreach(PropertyInfo prop in props) 10 { 11 Type t = GetCoreType(prop.PropertyType); 12 tb.Columns.Add(prop.Name, t); 13 } 14 15 foreach(T item in items) 16 { 17 var values = new object[props.Length]; 18 19 for (int i = 0; i < props.Length; i++) 20 { 21 values[i] = props[i].GetValue(item, null); 22 } 23 24 tb.Rows.Add(values); 25 } 26 27 return tb; 28 } 29 30 public static bool IsNullable(Type t) 31 { 32 return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable < > )); 33 } 34 35 public static Type GetCoreType(Type t) 36 { 37 if (t != null && IsNullable(t)) 38 { 39 if (!t.IsValueType) 40 { 41 return t; 42 } else { 43 return Nullable.GetUnderlyingType(t); 44 } 45 } else { 46 return t; 47 } 48 } 49 }