利用反射将Datatable转为List集合

public List<T> Show1<T>(DataTable dt)where T : class, new()
        {
            List<T> list = new List<T>();
            string ss = string.Empty;
            //获取类型
            Type tp = typeof(T);
            //遍历数据行
            foreach (DataRow item in dt.Rows)
            {
                T t = new T();
                //获取所有的公共属性
                PropertyInfo[] properties = tp.GetProperties();
                //遍历属性
                foreach (PropertyInfo aa in properties)
                {
                    //将属性名赋给变量
                    ss = aa.Name;
                    //
                    if (dt.Columns.Contains(ss))
                    {
                        //获取属性名所对应的值
                        object value = item[ss];
                        if (value != DBNull.Value)
                        {
                            //赋值
                            aa.SetValue(t, value, null);
                        }
                    }
                }
                list.Add(t);
            }
            dt.Clear();
            dt.Dispose();
            return list;
        }
原文地址:https://www.cnblogs.com/sange118/p/13139176.html