for (int i = 0; i < 5; i++) { DataRow dr = dt.NewRow(); dr["ID"] = i; dr["Name"] = "User" + i; dr["Weight"] = 25; dr["UpdateDate"] = DateTime.Now; dt.Rows.Add(dr); } return dt; }
//實際轉換的function publicstaticclassDataTableExtensions { publicstatic 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; }
privatestatic 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); } } elseif (property.PropertyType == typeof(decimal)) { decimal val = newdecimal(); decimal.TryParse(row[property.Name].ToString(), out val); property.SetValue(item, val, null); } elseif(property.PropertyType == typeof(double)) { double val = newdouble(); double.TryParse(row[property.Name].ToString(), out val); property.SetValue(item, val, null); } elseif (property.PropertyType == typeof(int)) { int val = newint(); 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();