自定義的class
- public class UserInfo
- {
- public int ID{get;set;}
- public string Name{get;set;}
- public double weight{get;set;}
- public DataTime UpdateDate{get;set;}
- }
而這是取得DataTable資料的function,為求Demo而塞一些假資料
- static private DataTable GetDataTable()
- {
- DataTable dt - new DataTable();
- dt.Columns.Add("ID");
- dt.Columns.Add("Name");
- dt.Columns.Add("weight");
- dt.Columns.Add("UpdateDate");
-
- for(int i=0;i<10;i++)
- {
- DataRow dr = dt.NewRow();
- dr["ID"] =i;
- dr["Name"]="User"+i;
- dr["weight"]=23;
- dr["UpdateDate"]=DateTime.Now;
- dt.Rows.Add(dr);
- }
- return dt;
- }
而實際轉換的function如下,而通常我會新增一個class,讓其他程式能共用
- public static class DataTableExtensions
- {
- public static IList<T> ToList<T>(this DataTable table) where T : new()
- {
- IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
- IList<T> result = new List<T>();
-
- //取得DataTable所有的row data
- foreach (var row in table.Rows)
- {
- var item = MappingItem<T>((DataRow)row, properties);
- result.Add(item);
- }
-
- return result;
- }
-
- private static T MappingItem<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
- {
- T item = new T();
- foreach (var property in properties)
- {
- if (row.Table.Columns.Contains(property.Name))
- {
- //針對欄位的型態去轉換
- if (property.PropertyType == typeof(DateTime))
- {
- DateTime dt = new DateTime();
- if (DateTime.TryParse(row[property.Name].ToString(), out dt))
- {
- property.SetValue(item, dt, null);
- }
- else
- {
- property.SetValue(item, null, null);
- }
- }
- else if (property.PropertyType == typeof(decimal))
- {
- decimal val = new decimal();
- decimal.TryParse(row[property.Name].ToString(), out val);
- property.SetValue(item, val, null);
- }
- else if(property.PropertyType == typeof(double))
- {
- double val = new double();
- double.TryParse(row[property.Name].ToString(), out val);
- property.SetValue(item, val, null);
- }
- else if (property.PropertyType == typeof(int))
- {
- int val = new int();
- int.TryParse(row[property.Name].ToString(), out val);
- property.SetValue(item, val, null);
- }
- else
- {
- if (row[property.Name] != DBNull.Value)
- {
- property.SetValue(item, row[property.Name], null);
- }
- }
- }
- }
- return item;
- }
- }
使用方式:
- List<UserInfo> list = new List<UserInfo>();
- DataTable dt = GetDataTable();
- var result = DataTableExtensions.ToList<UserInfo>(dt).ToList();
- list = result.OrderBy(c => c.UpdateDate).ToList();