c# datatable 通过反射转成泛型list

在C#中,可以使用反射来将DataTable转换为泛型列表。下面是一个示例代码,展示了如何使用反射来实现这个转换过程:

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Data;

public class DataConverter
{
    public List<T> ConvertDataTableToList<T>(DataTable dataTable) where T : new()
    {
        List<T> list = new List<T>();

        foreach (DataRow row in dataTable.Rows)
        {
            T item = new T();

            foreach (DataColumn column in dataTable.Columns)
            {
                var property = typeof(T).GetProperty(column.ColumnName);
                if (property != null && row[column] != DBNull.Value)
                {
                    property.SetValue(item, Convert.ChangeType(row[column], property.PropertyType), null);
                }
            }

            list.Add(item);
        }

        return list;
    }
}

在这个示例中,我们创建了一个名为DataConverter的类,其中包含一个泛型方法ConvertDataTableToList<T>。这个方法接收一个DataTable作为参数,并使用反射技术将其转换为指定类型的泛型列表。在方法中,我们使用foreach循环遍历DataTable的行和列,然后使用反射来动态设置对象的属性值。

使用这个DataConverter类,可以很容易地将DataTable转换为任何指定类型的泛型列表。例如,假设我们有一个名为Person的实体类:

csharp 复制代码
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

可以这样使用DataConverter类来将DataTable转换为List<Person>

csharp 复制代码
 // 创建一个DataTable实例
 DataTable dataTable = new DataTable("Person");

 // 添加列
 dataTable.Columns.Add("Id", typeof(int));
 dataTable.Columns.Add("Name", typeof(string));
 dataTable.Columns.Add("Age", typeof(int));

 // 添加行数据
 dataTable.Rows.Add(1, "John", 25);
 dataTable.Rows.Add(2, "Alice", 30);
 dataTable.Rows.Add(3, "Bob", 28);

 List<Person> personList = ConvertDataTableToList<Person>(dataTable);

在上面的示例中,我们根据Person类的属性结构,将DataTable中的数据转换为List<Person>。这种方法能够以通用的方式来转换任何实体类对应的DataTable为泛型列表,使代码更加灵活和可复用。

相关推荐
xiaowu0808 小时前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful10 小时前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide11 小时前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
gc_229913 小时前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty2716 小时前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
c#上位机19 小时前
wpf之TextBlock
c#·wpf
almighty271 天前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
almighty271 天前
C#实现导入CSV数据到List<T>的完整教程
c#·csv·格式转换·c#导入数据·csv数据导入
程序猿多布1 天前
Lua和C#比较
c#·lua
csdn_aspnet2 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore