zoukankan      html  css  js  c++  java
  • C# List转DataTable(支持匿名类型)

     /// <summary>
            /// List转成DataTable
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="varlist"></param>
            /// <returns></returns>
            public static DataTable ListToDataTable<T>(IEnumerable<T> varlist)
            {
                DataTable dtReturn = new DataTable();
                PropertyInfo[] oProps = null;
    
                if (varlist == null) return dtReturn;
    
                foreach (T rec in varlist)
                {
                    if (oProps == null)
                    {
                        oProps = rec.GetType().GetProperties();
                        foreach (PropertyInfo pi in oProps)
                        {
                            Type colType = pi.PropertyType;
    
                            if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                            == typeof(Nullable<>)))
                            {
                                colType = colType.GetGenericArguments()[0];
                            }
    
                            dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                        }
                    }
    
                    DataRow dr = dtReturn.NewRow();
    
                    foreach (PropertyInfo pi in oProps)
                    {
                        dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                        (rec, null);
                    }
    
                    dtReturn.Rows.Add(dr);
                }
                return dtReturn;
            }

    应用举例:

    量变会引起质变。
  • 相关阅读:
    spring学习(一)IOC&AOP
    MongoDB 写入数据的安全性
    MongoDB MapReduce
    MongoDB 原子操作
    MongoDB 文档间的关系
    MongoDB Java
    MongoDB 持久化
    MongoDB 聚合函数 aggregate
    MongoDB 索引
    MongoDB 文档操作
  • 原文地址:https://www.cnblogs.com/bibi-feiniaoyuan/p/list_totable.html
Copyright © 2011-2022 走看看