c#中DataTable轉(zhuǎn)List的2種方法示例
在項(xiàng)目中常常常使用到DataTable,假設(shè)DataTable使用得當(dāng),不僅能使程序簡潔有用,并且可以提高性能,達(dá)到事半功倍的效果,List<T>類是ArrayList類的泛型等效類,該類使用大小可按需動態(tài)增加的數(shù)組實(shí)現(xiàn)IList<T>泛型接口。這篇文章主要介紹了c# DataTable 轉(zhuǎn) List的兩種方法,下面來一起看看吧。
1. 直接寫一個(gè)datatable轉(zhuǎn)list的類
2. 利用泛型來寫,更加通用
public List<Dictionary<string, object>> DatatoTable(DataTable dt)
{
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.Rows)//每一行信息,新建一個(gè)Dictionary<string,object>,將該行的每列信息加入到字典
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
result.Add(dc.ColumnName, dr[dc].ToString());
}
list.Add(result);
}
return list;
}
public class TabletoList
{
public static List<T> TableToListModel<T>(DataTable dt) where T : new()
{
// 定義集合
List<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; // 檢查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判斷此屬性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
第二個(gè)方法在使用的時(shí)候需要注意:T為自己定義的類,其中的屬性需要與數(shù)據(jù)庫對應(yīng)
總結(jié)
到此這篇關(guān)于c#中DataTable轉(zhuǎn)List的2種方法的文章就介紹到這了,更多相關(guān)c# DataTable轉(zhuǎn)List內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C#中泛型舉例List<T>與DataTable相互轉(zhuǎn)換
- C#中將DataTable轉(zhuǎn)化成List<T>的方法解析
- C#實(shí)現(xiàn)DataTable,List和Json轉(zhuǎn)換的方法
- C#實(shí)現(xiàn)DataTable轉(zhuǎn)換成IList的方法
- C#將DataTable轉(zhuǎn)化為List<T>
- C#將DataTable轉(zhuǎn)換成list的方法
- c#的datatable轉(zhuǎn)list示例
- c#將list類型轉(zhuǎn)換成DataTable方法示例
- C#中DataTable和List互轉(zhuǎn)的示例代碼
相關(guān)文章
C#中實(shí)現(xiàn)輸入漢字獲取其拼音(漢字轉(zhuǎn)拼音)的2種方法
這篇文章主要介紹了C#中實(shí)現(xiàn)輸入漢字獲取其拼音(漢字轉(zhuǎn)拼音)的2種方法,本文分別給出了使用微軟語言包、手動編碼實(shí)現(xiàn)兩種實(shí)現(xiàn)方式,需要的朋友可以參考下2015-01-01
基于C#實(shí)現(xiàn)PDF按頁分割文件和分頁合并
iTextSharp 是一個(gè)開源的 PDF 處理庫,用于在 C# 程序中創(chuàng)建、編輯和處理 PDF 文件,本文將使用iTextSharp實(shí)現(xiàn)C# PDF分割與合并,感興趣的可以了解下2025-03-03
WPF仿三星手機(jī)充電界面實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了WPF仿三星手機(jī)充電界面實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08

