datatable填装List代替for循环
public class DataToModelHelper<T> where T : new() { public static IList<T> ConvertToModel(DataTable dt) { //定义集合 IList<T> ts = new List<T>(); T t = new T(); string tempName = ""; //获取此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (DataRow row in dt.Rows) { t = new T(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; //检查DataTable是否包含此列 if (dt.Columns.Contains(tempName)) { //判断此属性是否有set if (!pi.CanWrite) continue; object value = row[tempName]; if (value != DBNull.Value) { if (pi.PropertyType == typeof(string)) { pi.SetValue(t, value.ToString(), null); } else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?)) { pi.SetValue(t, int.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime)) { pi.SetValue(t, DateTime.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(float)) { pi.SetValue(t, float.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(double)) { pi.SetValue(t, double.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(decimal)) { pi.SetValue(t, decimal.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(Int64)) { pi.SetValue(t, long.Parse(value.ToString()), null); } else { pi.SetValue(t, value, null); } } } } ts.Add(t); } return ts; } }
posted on 2018-01-16 17:51 YellowCool 阅读(242) 评论(0) 编辑 收藏 举报