Efficiently convert IEnumerable to DataTable in C#
This article explores how to efficiently convert IEnumerable collections to DataTables. Although reflection provides a method, it is inefficient.
The following code provides a more optimized solution:
<code class="language-csharp">public static DataTable ToDataTable<T>(this IEnumerable<T> items) { // 创建DataTable并收集属性 DataTable table = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); // 从属性添加列 foreach (var prop in props) { Type propType = prop.PropertyType; // 处理可空类型 if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) propType = new NullableConverter(propType).UnderlyingType; table.Columns.Add(prop.Name, propType); } // 从属性值添加数据行 foreach (var item in items) { object[] values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } table.Rows.Add(values); } return table; }</code>
This extension method handles conversions efficiently, including handling nullable values. Consideration of nullable types ensures data integrity and reliable results.
The above is the detailed content of How to Efficiently Convert an IEnumerable to a DataTable in C#?. For more information, please follow other related articles on the PHP Chinese website!