通用的DataTable转换为List

c# code

 

///

/// 将DataTable转换为list /// /// /// /// public static IList DataTableToList(DataTable dt) { if (dt == null) return null; IList result = new List(); for (int j = 0; j < dt.Rows.Count; j++) { T _t = (T)Activator.CreateInstance(typeof(T)); PropertyInfo[] propertys = _t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { for (int i = 0; i < dt.Columns.Count; i++) { // 属性与字段名称一致的进行赋值 if (pi.Name.Equals(dt.Columns[i].ColumnName)) { if (dt.Rows[j][i] != DBNull.Value) { if (pi.PropertyType.ToString() == "System.Int32") { pi.SetValue(_t, Int32.Parse(dt.Rows[j][i].ToString()), null); } if (pi.PropertyType.ToString() == "System.DateTime") { pi.SetValue(_t, Convert.ToDateTime(dt.Rows[j][i].ToString()), null); } if (pi.PropertyType.ToString() == "System.String") { pi.SetValue(_t, dt.Rows[j][i].ToString(), null); } if (pi.PropertyType.ToString() == "System.Boolean") { pi.SetValue(_t, Convert.ToBoolean(dt.Rows[j][i].ToString()), null); } } else pi.SetValue(_t, null, null); break; } } } result.Add(_t); } return result; }

 

ps: 几个月没用csdn博客了,依然一如既往的磋,不容易啊....

 

你可能感兴趣的:(语言细节,null,list,c#)