在项目中常常常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,List<T>类是ArrayList类的泛型等效类,该类使用大小可按需动态增加的数组实现IList<T>泛型接口。这篇文章主要介绍了c# DataTable 转 List的两种方法,下面来一起看看吧。
1. 直接写一个datatable转list的类
2. 利用泛型来写,更加通用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public List<Dictionary< string , object >> DatatoTable(DataTable dt) { List<Dictionary< string , object >> list = new List<Dictionary< string , object >>(); foreach (DataRow dr in dt.Rows) //每一行信息,新建一个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; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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; } } |
第二个方法在使用的时候需要注意:T为自己定义的类,其中的属性需要与数据库对应
总结
到此这篇关于c#中DataTable转List的2种方法的文章就介绍到这了,更多相关c# DataTable转List内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/chenweilong213/article/details/115578126