C#中泛型舉例List<T>與DataTable相互轉(zhuǎn)換
更新時(shí)間:2022年05月11日 08:07:05 作者:springsnow
這篇文章介紹了C#中泛型舉例List<T>與DataTable相互轉(zhuǎn)換的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
一、 DataTable轉(zhuǎn)換到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;
}
}應(yīng)用:
// 獲得查詢結(jié)果
DataTable dt = DbHelper.ExecuteDataTable("...");
// 把DataTable轉(zhuǎn)換為IList<UserInfo>
IList<UserInfo> users = TableListConverter<UserInfo>.TableToList(dt);二、 List<T>轉(zhuǎn)換到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;
}
}應(yīng)用:
//IList<UserInfo> users DataTable dt =TableListConverter.ListToTable(users)


到此這篇關(guān)于C#中泛型舉例List<T>與DataTable相互轉(zhuǎn)換的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解析C#中委托的同步調(diào)用與異步調(diào)用(實(shí)例詳解)
本篇文章是對(duì)C#中委托的同步調(diào)用與異步調(diào)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C#中的SQLCommand命令與DbTransaction事務(wù)處理
這篇文章介紹了C#中的SQLCommand命令與DbTransaction事務(wù)處理,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05

