一,
/// <summary> /// 將Datatable轉換為List集合 /// </summary> /// <typeparam name="T">類型參數</typeparam> /// <param name="dt">datatable表</param> /// <returns></returns> public static List<T> DataTableToList<T>(DataTable dt) { var list = new List<T>(); Type t = typeof(T); var plist = new List<PropertyInfo>(typeof(T).GetProperties()); foreach (DataRow item in dt.Rows) { T s = System.Activator.CreateInstance<T>(); for (int i = 0; i < dt.Columns.Count; i++) { PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName); if (info != null) { if (!Convert.IsDBNull(item[i])) { info.SetValue(s, item[i], null); } } } list.Add(s); } return list; }
二,
public static IList<T> convertToList<T>(DataTable dt) where T : new()
8 {
9 // 定義集合
10 List<T> ts = new List<T>();
11
12 // 獲得此模型的類型
13 Type type = typeof(T);
14 //定義一個臨時變量
15 string tempName = string.Empty;
16 //遍歷DataTable中所有的數據行
17 foreach (DataRow dr in dt.Rows)
18 {
19 T t = new T();
20 // 獲得此模型的公共屬性
21 PropertyInfo[] propertys = t.GetType().GetProperties();
22 //遍歷該對象的所有屬性
23 foreach (PropertyInfo pi in propertys)
24 {
25 tempName = pi.Name;//將屬性名稱賦值給臨時變量
26 //檢查DataTable是否包含此列(列名==對象的屬性名)
27 if (dt.Columns.Contains(tempName))
28 {
29 // 判斷此屬性是否有Setter
30 if (!pi.CanWrite) continue;//該屬性不可寫,直接跳出
31 //取值
32 object value = dr[tempName];
33 //如果非空,則賦給對象的屬性
34 if (value != DBNull.Value)
35 pi.SetValue(t, value, null);
36 }
37 }
38 //對象添加到泛型集合中
39 ts.Add(t);
40 }
41 return ts;
42 }
三,
1.DataTable到List<T>的轉換
public static List<T> DataTableToT<T>(DataTable source) where T : class, new()
{
List<T> itemlist = null;
if (source == null || source.Rows.Count == 0)
{
return itemlist;
}
itemlist = new List<T>();
T item = null;
Type targettype = typeof(T);
Type ptype = null;
Object value = null;
foreach (DataRow dr in source.Rows)
{
item = new T();
foreach (PropertyInfo pi in targettype.GetProperties())
{
if (pi.CanWrite && source.Columns.Contains(pi.Name))
{
ptype = Type.GetType(pi.PropertyType.FullName);
value = Convert.ChangeType(dr[pi.Name], ptype);
pi.SetValue(item, value, null);
}
}
itemlist.Add(item);
}
return itemlist;
}
2.DataRow到T的轉換
public static T DataRowToT<T>(DataRow source) where T:class,new()
{
T item = null;
if (source == null)
{
return item;
}
item = new T();
Type targettype = typeof(T);
Type ptype = null;
Object value = null;
foreach (PropertyInfo pi in targettype.GetProperties())
{
if (pi.CanWrite && source.Table.Columns.Contains(pi.Name))
{
ptype = Type.GetType(pi.PropertyType.FullName);
value = Convert.ChangeType(source[pi.Name], ptype);
pi.SetValue(item, value, null);
}
}
return item;
}