首页 > 其他 > 详细

利用反射将Datatable转为List集合

时间:2020-06-16 09:33:01      阅读:60      评论:0      收藏:0      [点我收藏+]
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;
        }

利用反射将Datatable转为List集合

原文:https://www.cnblogs.com/sange118/p/13139176.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!