C# DataTable 转换成List<T>

本文提供了一段实用的C#代码,用于将DataTable转换为List<T>。通过运用泛型和反射技术,该方法能够高效地完成数据类型的转换,并针对可空类型进行了特别优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运用泛型和反射实现的转换,很给力。代码中掺杂详尽注释,稍微了解一下泛型和反射便可以了解转换的实质。可以直接复制粘贴进行调用哦。

//这个方法对可空类型的支持不是很好。
public
class DtConverToList<T> where T : new() { public static List<T> DtToList(DataTable dt) { //定义集合 List<T> ListCollection = new List<T>(dt.Rows.Count); //获得 T 模型类型 Type T_type = typeof(T); //获得 T 模型类型公共属性 PropertyInfo[] Proper = T_type.GetProperties(); //临时变量,存储变量模型公共属性Name string Tempname = ""; //遍历参数 DataTable的每行 foreach (DataRow Dr in dt.Rows) { //实例化 T 模版类 T t = new T(); //遍历T 模版类各个属性 #region foreach (PropertyInfo P in Proper) { //取出类属性之一 Tempname = P.Name; //判断DataTable中是否有此列 if (dt.Columns.Contains(Tempname)) { //判断属性是否可写属性 if (!P.CanWrite) { continue; } try { //得到Datable单元格中的值 object value = Dr[Tempname]; //得到 T 属性类型 Type ProType = P.PropertyType; //判断类型赋值 if (value != DBNull.Value) { // if (value.GetType() == ProType) { P.SetValue(t, value, null); } else { if (ProType == typeof(string)) { string Temp = value.ToString(); P.SetValue(t, Temp, null); } else if (ProType == typeof(byte)) { byte Temp = Convert.ToByte(value); P.SetValue(t, Temp, null); } else if (ProType == typeof(short)) { short Temp = short.Parse(value.ToString()); P.SetValue(t, Temp, null); } else if (ProType == typeof(long)) { long Temp = long.Parse(value.ToString()); P.SetValue(t, Temp, null); } else if (ProType == typeof(Int64)) { Int64 Temp = Convert.ToInt64(value); P.SetValue(t, Temp, null); } else if (ProType == typeof(Int32)) { Int32 Temp = Convert.ToInt32(value); P.SetValue(t, Temp, null); } else if (ProType == typeof(Int16)) { Int16 Temp = Convert.ToInt16(value); P.SetValue(t, Temp, null); } else { object Temp = Convert.ChangeType(value, ProType); P.SetValue(t, Temp, null); } } } } catch (Exception) { throw; } } } #endregion ListCollection.Add(t); } return ListCollection; } }

这个可以支持可空类型

public class ModelConvertHelper<T> where T : new() // 此处一定要加上new()
{


public static IList<T> ConvertToModel(DataTable dt)
{


IList<T> ts = 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 pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}

 

 

转载于:https://www.cnblogs.com/yangkangIT/p/4632431.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值