using System;
using System.Collections.Generic;
using System.Data;
public class DataTableToListExample
{
public static List<T> ConvertDataTableToList<T>(DataTable dt) where T : new()
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = new T();
foreach (PropertyInfo prop in item.GetType().GetProperties())
{
if (dt.Columns.Contains(prop.Name))
{
prop.SetValue(item, row[prop.Name], null);
}
}
data.Add(item);
}
return data;
}
}
ConvertDataTableToList<T>:此方法接受一个 DataTable 作为参数,并返回一个 List<T>,其中 T 是你需要转换的目标类型。where T : new():确保目标类型 T 必须有一个无参构造函数,以便在代码中通过 new T() 创建实例。DataTable 的每一行:使用 foreach (DataRow row in dt.Rows) 来遍历 DataTable 中的每一行。T 类型的实例。DataTable 是否包含对应的列名。如果包含,则将该列的值赋给属性。这个方法可以将任何 DataTable 转换为指定类型的列表,前提是目标类型的属性名与 DataTable 的列名相匹配。
上一篇:c# web开发
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站