首页 > 代码库 > 扩展方法(DateTableToList)

扩展方法(DateTableToList)

     public static IList<T> ToList<T>(this DataTable dt) where T : class,new()
        {
            var prlist = new List<PropertyInfo>();
            var t = typeof(T);
            Array.ForEach(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            var oblist = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                var ob = new TResult();
                prlist.ForEach(p => { if (row != null && row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
                oblist.Add(ob);
            }
            return oblist;
        }