将List转换为DataTable

本文介绍了一种将List集合转换为DataTable的方法。通过反射获取泛型类型的所有公共属性,并据此创建DataTable对象,然后填充数据行。适用于.NET环境中数据展示或转换的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    下面是一段将List转换为DataTable的方法,经常用到,希望对读者有帮助。

//将List转换为DataTable
        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;
        }
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }



### 将 C# 中的 `List` 转换为 `DataTable` 为了将泛型列表转换成 `DataTable`,可以通过遍历列表并动态创建表结构来实现。下面是一个通用方法的例子,该例子展示了如何将任何实现了 `IEnumerable<T>` 接口的对象集合转储到 `DataTable` 中。 ```csharp using System; using System.Collections.Generic; using System.Data; using System.Reflection; public static class ListExtensions { public static DataTable ToDataTable<T>(this IEnumerable<T> items) where T : class { var table = new DataTable(typeof(T).Name); // 获取属性信息用于列定义 PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { Type propertyType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; table.Columns.Add(prop.Name, propertyType); } foreach (T item in items) { DataRow row = table.NewRow(); foreach (PropertyInfo prop in props) { row[prop.Name] = prop.GetValue(item, null) ?? DBNull.Value; } table.Rows.Add(row); } return table; } } ``` 此扩展方法能够接受任意类型的对象列表,并基于这些对象公共属性自动生成相应的 `DataTable` 结构[^1]。 对于特定场景下的应用实例: 假设有一个简单的实体类表示记录项 ```csharp public class RecordItem { public int Id { get; set; } public string Name { get; set; } } // 使用示例 void Main() { var records = new List<RecordItem>() { new RecordItem{Id=1, Name="one"}, new RecordItem{Id=2, Name="two"} }; DataTable dt = records.ToDataTable(); Console.WriteLine(dt.AsEnumerable().CopyToDataTable()); } ``` 这段代码会输出由给定 `records` 集合构建而成的数据表格形式的内容[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值