.NET怎么将DataTable转换为List对象

来源:这里教程网 时间:2026-02-21 17:29:30 作者:

在 .NET 中,将 DataTable 转换为 List 是一个常见需求,尤其在处理数据库查询结果时。最常用的方式是通过反射(Reflection)将 DataTable 的每一行映射到一个强类型的对象中。

1. 定义目标类(Model)

假设你有一个 DataTable,包含姓名和年龄字段,先创建对应的类:

public class Person { public string Name { get; set; } public int Age { get; set; } }

2. 使用反射实现转换方法

下面是一个通用方法,可将任意 DataTable 转为 List

using System; using System.Collections.Generic; using System.Data; using System.Reflection; public static List DataTableToList(DataTable dt) where T : new() { List list = new List(); foreach (DataRow row in dt.Rows) { T item = new T(); foreach (DataColumn col in dt.Columns) { // 获取类中的属性 PropertyInfo prop = typeof(T).GetProperty(col.ColumnName); if (prop != null && prop.CanWrite) { object value = row[col]; if (value != DBNull.Value) { // 处理值类型转换(如 int?、DateTime? 等) Type propType = prop.PropertyType; if (Nullable.GetUnderlyingType(propType) is Type nullableType) propType = nullableType; object safeValue = Convert.ChangeType(value, propType); prop.SetValue(item, safeValue, null); } } } list.Add(item); } return list; }

3. 使用示例

调用这个方法非常简单:

// 假设 dt 是你的 DataTable DataTable dt = GetDataTable(); // 模拟获取数据 List people = DataTableToList(dt); foreach (var p in people) { Console.WriteLine($"姓名: {p.Name}, 年龄: {p.Age}"); }

4. 注意事项

列名必须与类的属性名完全匹配(包括大小写)。 支持可空类型(如 int?、DateTime?),代码中已做兼容处理。 性能敏感场景建议使用表达式树或手动映射提升效率。 如果字段多或数据量大,可以考虑使用 AutoMapperFastMember 等库优化。 基本上就这些。这种方法简单直接,适合大多数中小型项目使用。

相关推荐