调用:
List<BASEINFO> mar = DataTableToIList<BASEINFO>(myData.Tables[0]).ToList<BASEINFO>();
DataTableToIList方法:
/// <summary> /// DataTable转为List<T> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static IList<T> DataTableToIList<T>(DataTable table) { IList<T> result = new List<T>(); for (int j = 0; j < table.Rows.Count; j++) { T _t = (T)Activator.CreateInstance(typeof(T)); PropertyInfo[] propertys = _t.GetType().GetProperties(); foreach (PropertyInfo p in propertys) { if (!table.Columns.Contains(p.Name)) continue; if (string.IsNullOrEmpty(table.Rows[j][p.Name].ToString())) continue; //Type t = p.PropertyType; //MethodInfo m = t.GetMethod("TryParse"); switch (p.PropertyType.Name) { case "Int32": p.SetValue(_t, Int32.Parse(table.Rows[j][p.Name].ToString())); break; case "Int64": p.SetValue(_t, Int64.Parse(table.Rows[j][p.Name].ToString())); break; case "Decimal": p.SetValue(_t, Decimal.Parse(table.Rows[j][p.Name].ToString())); break; case "Double": p.SetValue(_t, Double.Parse(table.Rows[j][p.Name].ToString())); break; case "DateTime": p.SetValue(_t, DateTime.Parse(table.Rows[j][p.Name].ToString())); break; default: p.SetValue(_t, table.Rows[j][p.Name].ToString()); break; } } result.Add(_t); } return result; }