C#中泛型舉例List<T>與DataTable相互轉(zhuǎn)換
一、 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)換的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#連接Oracle數(shù)據(jù)庫使用Oracle.ManagedDataAccess.dll
這篇文章主要介紹了C#使用Oracle.ManagedDataAccess.dll的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11
C#中判斷字符串是全角還是半角的實(shí)現(xiàn)代碼
本篇文章主要是對C#中判斷字符串是全角還是半角的實(shí)現(xiàn)代碼進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01
C#?wpf定義ViewModelBase進(jìn)行簡化屬性綁定
綁定機(jī)制是wpf的核心,也是界面獨(dú)立的根本,尤其是使用了mvvm模式,本文主要介紹了wpf如何定義ViewModelBase進(jìn)行簡化屬性綁定,需要的可以參考下2024-04-04
WPF實(shí)現(xiàn)帶篩選功能的DataGrid
在默認(rèn)情況下,WPF提供的DataGrid僅擁有數(shù)據(jù)展示等簡單功能,如果要實(shí)現(xiàn)像Excel一樣復(fù)雜的篩選過濾功能,則相對比較麻煩。本文以一個(gè)簡單的小例子,簡述如何通過WPF實(shí)現(xiàn)DataGrid的篩選功能,僅供學(xué)習(xí)分享使用,如有不足之處,還請指正2023-03-03
C# .NET實(shí)現(xiàn)掃描識別圖片中的文字
本文以C#及VB.NET代碼為例,介紹如何掃描并讀取圖片中的文字。文中的示例代碼介紹詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2021-12-12
C#?BitArray(點(diǎn)矩陣)轉(zhuǎn)換成int和string的方法實(shí)現(xiàn)
BitArray?類管理一個(gè)緊湊型的位值數(shù)組,它使用布爾值來表示,本文主要介紹了C#?BitArray(點(diǎn)矩陣)轉(zhuǎn)換成int和string的方法實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2022-05-05
在.NET框架使用C#實(shí)現(xiàn)PDF文件轉(zhuǎn)為HTML格式的步驟
HTML作為一種開放標(biāo)準(zhǔn)的網(wǎng)頁標(biāo)記語言,具有跨平臺(tái)、易于瀏覽和搜索引擎友好的特性,通過將PDF文件轉(zhuǎn)換為HTML格式,我們可以更方便地在瀏覽器中展示PDF文檔內(nèi)容,本文將介紹如何在.NET框架使用C#將PDF文件轉(zhuǎn)換為HTML格式,需要的朋友可以參考下2025-01-01

