zoukankan      html  css  js  c++  java
  • 将泛类型集合List类转换成DataTable

            /// <summary>
            /// 将泛类型集合List类转换成DataTable
            /// </summary>
            /// <param name="list">泛类型集合</param>
            /// <returns></returns>
            public DataTable ListToDataTable<T>(List<T> entitys)
            {
                //检查实体集合不能为空
                if (entitys == null || entitys.Count < 1)
                {
                    throw new Exception("需转换的集合为空");
                }
                //取出第一个实体的所有Propertie
                Type entityType = entitys[0].GetType();
                PropertyInfo[] entityProperties = entityType.GetProperties();

                //生成DataTable的structure
                //生产代码中,应将生成的DataTable结构Cache起来,此处略
                DataTable dt = new DataTable();
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                    dt.Columns.Add(entityProperties[i].Name);
                }
                //将所有entity添加到DataTable中
                foreach (object entity in entitys)
                {
                    //检查所有的的实体都为同一类型
                    if (entity.GetType() != entityType)
                    {
                        throw new Exception("要转换的集合元素类型不一致");
                    }
                    object[] entityValues = new object[entityProperties.Length];
                    for (int i = 0; i < entityProperties.Length; i++)
                    {
                        entityValues[i] = entityProperties[i].GetValue(entity, null);
                    }
                    dt.Rows.Add(entityValues);
                }
                return dt;
            }

  • 相关阅读:
    手打AC的第2道数位DP:BZOJ1799: [Ahoi2009]self 同类分布
    Oracle PL/SQL编程基础
    Oracle高级查询,事物,过程及函数
    缓存技术
    图形化报表
    网站配置与部署
    Oracle 空间管理
    Oracle 10g体系结构及安全管理
    ORACLE 数据库概述
    jQuery中的Ajax应用
  • 原文地址:https://www.cnblogs.com/yhongl/p/3937932.html
Copyright © 2011-2022 走看看