这篇文章介绍了C#中泛型举例ListT与DataTable相互转换的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、 DataTable转换到List<T>
/// <summary>
/// TableToList
/// </summary>
public class TableListConverter<T> where T : class, new()
{
public static IList<T> TableToList(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))// 检查DataTable是否包含此列
{
if (!pi.CanWrite) continue;// 判断此属性是否有Setter
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
应用:
// 获得查询结果
DataTable dt = DbHelper.ExecuteDataTable("...");
// 把DataTable转换为IList<UserInfo>
IList<UserInfo> users = TableListConverter<UserInfo>.TableToList(dt);
二、 List<T>转换到DataTable
/// <summary>
/// ListToTable
/// </summary>
public class TableListConverter
{
public static DataTable ListToTable<T>(IList<T> list) where T : class, new()
{
if (list == null) return null;
Type type = typeof(T);
DataTable dt = new DataTable();
PropertyInfo[] properties = Array.FindAll(type.GetProperties(), p => p.CanRead);//判断此属性是否有Getter
Array.ForEach(properties, prop => { dt.Columns.Add(prop.Name, prop.PropertyType); });//添加到列
foreach (T t in list)
{
DataRow row = dt.NewRow();
Array.ForEach(properties, prop =>
{
row[prop.Name] = prop.GetValue(t, null);
});//添加到行
dt.Rows.Add(row);
}
return dt;
}
}
应用:
//IList<UserInfo> users
DataTable dt =TableListConverter.ListToTable(users)
到此这篇关于C#中泛型举例List<T>与DataTable相互转换的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:C#中泛型举例List<T>与DataTable相互转换


基础教程推荐
猜你喜欢
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- Unity shader实现高斯模糊效果 2023-01-16
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C# 解析XML和反序列化的示例 2023-04-14
- C#中 Json 序列化去掉null值的方法 2022-11-18
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中的Linq to JSON操作详解 2023-06-08
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#调用摄像头实现拍照功能的示例代码 2023-03-09