using System;
using System.Collections.Generic;
using System.Data;
public class ConvertTool
{
public static List<T> DataConvert<T>(DataTable tb)
{
List<T> lst = new List<T>();
DataConvert<T>(tb, ref lst);
return lst;
}
public static List<T> DataConvert<T>(DataTable tb, ref List<T> lst)
{
for (int i = 0; i < tb.Rows.Count; i++)
{
lst.Add(DataConvert<T>(tb.Rows[i]));
}
return lst;
}
public static T DataConvert<T>(DataRow row)
{
var type = typeof(T);
object obj = type.Assembly.CreateInstance(type.FullName);
var c = (T)obj;
DataConvert(row, ref c);
return c;
}
public static T DataConvert<T>(DataRow row, ref T t)
{
var ps = t.GetType().GetProperties();
var tbColumns = row.Table.Columns;
foreach (var c in ps)
{
var colName = c.Name;
if (tbColumns.Contains(colName))
{
object nr = row[colName] == DBNull.Value ? null : row[colName];
if (nr == null)
{
c.SetValue(t, nr, null);
}
else
{
var nrType = c.PropertyType;
if (nrType == typeof(decimal) || nrType == typeof(decimal?))
{
nr = Convert.ToDecimal(nr);
}
else if (nrType == typeof(Int64) || nrType == typeof(Int64?))
{
nr = Convert.ToInt64(nr);
}
else if (nrType == typeof(double) || nrType == typeof(double?))
{
nr = Convert.ToDouble(nr);
}
else if (nrType == typeof(Int32) || nrType == typeof(Int32?))
{
nr = Convert.ToInt32(nr);
}
else if (nrType == typeof(Int16) || nrType == typeof(Int16?))
{
nr = Convert.ToInt16(nr);
}
c.SetValue(t, nr, null);
}
}
}
return t;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界