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;
            }
  • 相关阅读:
    [BZOJ3223] [Tyvj1729] 文艺平衡树 (splay)
    [BZOJ3098] Hash Killer II
    [BZOJ3000] Big Number (Stirling公式)
    [BZOJ2048] [2009国家集训队] 书堆
    [BZOJ1707] [Usaco2007 Nov] tanning分配防晒霜 (贪心)
    BZOJ2482: [Spoj1557] Can you answer these queries II
    BZOJ2157: 旅游
    BZOJ2795: [Poi2012]A Horrible Poem
    BZOJ3681: Arietta
    BZOJ3218: a + b Problem
  • 原文地址:https://www.cnblogs.com/sange118/p/13139176.html
Copyright © 2011-2022 走看看