zoukankan      html  css  js  c++  java
  • 利用反射将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;
            }
  • 相关阅读:
    mysql面试知识点
    计算机网络
    BFS
    拓扑排序
    双指针
    回溯算法
    hash表 算法模板和相关题目
    桶排序及其应用
    滑动窗口
    贪心算法
  • 原文地址:https://www.cnblogs.com/sange118/p/13139176.html
Copyright © 2011-2022 走看看