zoukankan      html  css  js  c++  java
  • 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;
            }

    应用举例:

  • 相关阅读:
    基于Centos 7 vue+nginx+docker 的前端项目部署
    uni-app学习随笔
    微服务和Docker
    Ado.Net
    数据库(SQLServer)
    JavaScript
    CSS样式
    HTML前端标签
    vue中 拖动元素边框 改变元素宽度
    vue学习笔记14
  • 原文地址:https://www.cnblogs.com/bibi-feiniaoyuan/p/13851948.html
Copyright © 2011-2022 走看看