C#中高效将IEnumerable转换为DataTable
本文探讨如何高效地将IEnumerable集合转换为DataTable。虽然反射提供了一种方法,但它效率低下。
以下代码提供了一种更优化的解决方案:
<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>
此扩展方法高效地处理转换,包括处理可空值。对可空类型的考虑确保了数据完整性和可靠的结果。
以上是如何在 C# 中高效地将 IEnumerable 转换为 DataTable?的详细内容。更多信息请关注PHP中文网其他相关文章!