方案一:
使用泛型和反射相关知识
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace APIUpLoadData
{
public class ToolsHelper<T> where T : new() // 此处一定要加上new()
{
public static IList<T> DataTableToModel(DataTable dt)
{
IList<T> list = new List<T>();// 定义集合
Type type = typeof(T); // 获得此模型的类型
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pro in propertys)
{
tempName = pro.Name;
if (dt.Columns.Contains(tempName))
{
if (!pro.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pro.SetValue(t, value, null);
}
}
list.Add(t);
}
return list;
}
}
}
方案二:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APIUpLoadData
{
public class PlastiaBoxModel
{
public string cusName { get; set; }
public string cusAge { get; set; }
public string cusSex { get; set; }
}
}
public static List<PlastiaBoxModel> Tolist(DataTable dt)
{
List<PlastiaBoxModel> list = new List<PlastiaBoxModel>();
PlastiaBoxModel box = new PlastiaBoxModel();
foreach (DataRow dr in dt.Rows)
{
box.cusName = dr["cusName"].ToString();
box.cusAge = dr["cusAge"].ToString();
box.cusSex = dr["cusSex"].ToString();
list.Add(box);
}
return list;
}
///调用方法
//dt----datatable数据
List<PlastiaBoxModel> list=Program.Tolist(dt);