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为泛型列表,使代码更加灵活和可复用。

相关推荐
JustCheng8 小时前
Dispacher(1/2)深入解析-详细使用
c#
CoderIsArt21 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
呆呆敲代码的小Y1 天前
【游戏开发】Lua 与 C# 交互原理解析
c#·lua·交互·热更新·lua与c#交互·游戏热更新
叼烟扛炮1 天前
C++第十讲:list
list
用户298698530141 天前
PDF 转纯文本(TXT)免费攻略:轻松提取文字内容
人工智能·后端·c#
呆呆敲代码的小Y1 天前
【游戏开发】C# 中的迭代器
java·开发语言·c#·迭代器
格林威2 天前
C# 相机Burst模式图像采集:使用相机内存配合OpenCvSharp和Halcon实现短时间的高速采集的方法
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
J总裁的小芒果2 天前
参数过多-分批传参
c#
典典分享指南2 天前
短视频分镜提示词:让 AI 出片的产品口播
java·c#·bash·composer·symfony