using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; namespace Tiobon.Core.OPS.Tool.OPS.Tool.Helper { public static class Convetdata { public static List ToList(this DataTable dt) where T : class, new() { Type t = typeof(T); PropertyInfo[] propertys = t.GetProperties(); List lst = new List(); string typeName = string.Empty; foreach (DataRow dr in dt.Rows) { T entity = new T(); foreach (PropertyInfo pi in propertys) { typeName = pi.Name; if (dt.Columns.Contains(typeName)) { if (!pi.CanWrite) continue; object value = dr[typeName]; if (value == DBNull.Value) continue; if (pi.PropertyType == typeof(string)) { pi.SetValue(entity, value.ToString(), null); } else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?)) { pi.SetValue(entity, int.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime)) { pi.SetValue(entity, DateTime.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(float)) { pi.SetValue(entity, float.Parse(value.ToString()), null); } else if (pi.PropertyType == typeof(double)) { pi.SetValue(entity, double.Parse(value.ToString()), null); } else { pi.SetValue(entity, value, null); } } } lst.Add(entity); } return lst; } public static void ForEach(this IEnumerable ien, Action express) { foreach (var item in ien) { express(item); } } public static DataTable ToDataTable(this IEnumerable value) where T : class, new() { List lstProperty = new List(); Type type = typeof(T); DataTable dt = new DataTable(); type.GetProperties().ForEach(p => //ForEach扩展方法,这里使用Array.ForEach(type.GetProperties(),p=>{})也是一样 { lstProperty.Add(p); if (p.PropertyType.IsGenericType)//是否为泛型,泛型获取不到具体的类型 { dt.Columns.Add(p.Name); } else { dt.Columns.Add(p.Name, p.PropertyType); } }); if (value != null) { foreach (var item in value) { //创建一个DataRow实例 DataRow row = dt.NewRow(); lstProperty.ForEach(p => { row[p.Name] = p.GetValue(item, null); }); dt.Rows.Add(row); } } return dt; } } }