介绍:List/IEnumerable转换到DataTable/DataView,以及DataTable转换到List
正文:
一、List<T>/IEnumerable转换到DataTable/DataView
方法一:
1 /// <summary> 2 /// Convert a List{T} to a DataTable. 3 /// </summary> 4 private DataTable ToDataTable<T>(List<T> items) 5 { 6 var tb = new DataTable(typeof (T).Name); 7 8 PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 9 10 foreach (PropertyInfo prop in props) 11 { 12 Type t = GetCoreType(prop.PropertyType); 13 tb.Columns.Add(prop.Name, t); 14 } 15 16 foreach (T item in items) 17 { 18 var values = new object[props.Length]; 19 20 for (int i = 0; i < props.Length; i++) 21 { 22 values[i] = props[i].GetValue(item, null); 23 } 24 25 tb.Rows.Add(values); 26 } 27 28 return tb; 29 } 30 31 /// <summary> 32 /// Determine of specified type is nullable 33 /// </summary> 34 public static bool IsNullable(Type t) 35 { 36 return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); 37 } 38 39 /// <summary> 40 /// Return underlying type if type is Nullable otherwise return the type 41 /// </summary> 42 public static Type GetCoreType(Type t) 43 { 44 if (t != null && IsNullable(t)) 45 { 46 if (!t.IsValueType) 47 { 48 return t; 49 } 50 else 51 { 52 return Nullable.GetUnderlyingType(t); 53 } 54 } 55 else 56 { 57 return t; 58 } 59 }