首页 > 后端开发 > C++ > 如何在 C# 中高效地将 IEnumerable 转换为 DataTable?

如何在 C# 中高效地将 IEnumerable 转换为 DataTable?

Mary-Kate Olsen
发布: 2025-01-20 00:24:14
原创
580 人浏览过

How to Efficiently Convert an IEnumerable to a DataTable in C#?

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板