本文主要是介绍集合转DataTable,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
region List to a DataTable
/// <summary>/// List<T>集合转换成DataTable/// </summary>private DataTable ToDataTable<T>(List<T> items){var tb = new DataTable(typeof(T).Name);PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);foreach (PropertyInfo prop in props){Type t = GetCoreType(prop.PropertyType);tb.Columns.Add(prop.Name, t);}foreach (T item in items){var values = new object[props.Length];for (int i = 0; i < props.Length; i++){values[i] = props[i].GetValue(item, null);}tb.Rows.Add(values);}return tb;}/// <summary>/// 指定类型的确定是否为空/// </summary>public static bool IsNullable(Type t){return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));}/// <summary>/// 如果类型为空否则返回类型返回基本类型/// </summary>public static Type GetCoreType(Type t){if (t != null && IsNullable(t)){if (!t.IsValueType){return t;}else{return Nullable.GetUnderlyingType(t);}}else{return t;}}#endregion
这篇关于集合转DataTable的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!