定义Person类包含Name和Age属性;2. 使用反射遍历DataTable行与列,通过GetProperty匹配属性并转换值类型,支持可空类型;3. 调用DataTableToList方法将DataTable转为List并输出结果;4. 注意列名需与属性名一致,性能敏感场景建议优化。该方法适用于中小型项目。
在 .NET 中,将 DataTable 转换为 List
假设你有一个 DataTable,包含姓名和年龄字段,先创建对应的类:
public class Person { public string Name { get; set; } public int Age { get; set; } }下面是一个通用方法,可将任意 DataTable 转为 List
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;
}
调用这个方法非常简单:
// 假设 dt 是你的 DataTable DataTable dt = GetDataTable(); // 模拟获取数据 List