1:model转datatable
public static DataTable ListToDataTable<T>(List<T> entitys)
{
if (entitys == null || entitys.Count < 1)
{
throw new ArgumentException("需转换的集合为空");
}
Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
DataTable dt = new DataTable();
foreach (var prop in entityProperties)
{
if (prop.CanRead) // 确保属性可读
{
dt.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
foreach (T entity in entitys) // 使用泛型类型参数以避免装箱
{
if (entity.GetType() != entityType)
{
throw new ArgumentException("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
try
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
catch (Exception ex)
{
// 处理或记录异常
Console.WriteLine($"无法获取属性 {entityProperties[i].Name} 的值: {ex.Message}");
entityValues[i] = DBNull.Value; // 或其他默认值
}
}
dt.Rows.Add(entityValues);
}
return dt;
}
2:datatalbe 转model
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
public static class DataTableExtensions
{
public static List<T> DataTableToList<T>(DataTable dt) where T : new()
{
var list = new List<T>();
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (DataRow row in dt.Rows)
{
var item = new T();
foreach (var prop in props)
{
// 假设DataTable的列名和Model的属性名相同
if (dt.Columns.Contains(prop.Name))
{
// 尝试将DataRow中的值转换为属性类型
try
{
// 使用Convert.ChangeType来处理类型转换
object value = row[prop.Name];
if (value != DBNull.Value)
{
value = Convert.ChangeType(value, prop.PropertyType);
prop.SetValue(item, value, null);
}
}
catch (Exception ex)
{
// 处理或记录类型转换失败的情况
Console.WriteLine($"无法将值转换为 {prop.PropertyType.Name} 类型: {ex.Message}");
}
}
}
list.Add(item);
}
return list;
}
}
// 使用示例
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
// ...
DataTable dt = // 假设这里有一个DataTable,包含"Name"和"Age"列
List<Person> people = DataTableExtensions.DataTableToList<Person>(dt);