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

相关推荐
zdr尽职尽责1 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
BruceNeter3 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
wo_jack3 天前
C++ 入门笔记(十八):list 进阶 —— const 迭代器、operator-> 与 clear 的坑
数据结构·c++·面试·stl·list
2601_967980113 天前
python list如何赋值
python·list·列表推导式·赋值·切片赋值
何以解忧唯有撸码4 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
国家一级摸鱼选手5 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库5 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc5 天前
C# 发展历史
开发语言·c#
kyle~5 天前
C# --- 反射
开发语言·c#
暴走约伯6 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质