度量快速开发平台-专业、快速的软件定制快开平台

标题: List转换DataTable [打印本页]

作者: 张兴康    时间: 2020-5-15 17:09
标题: List转换DataTable
  1. /// <summary>
  2.     /// 将泛类型集合List类转换成DataTable
  3.     /// </summary>
  4.     /// <param name="list">泛类型集合</param>
  5.     /// <returns></returns>
  6.     public static DataTable ListToDataTable<T>(List<T> entitys)
  7.     {
  8.         //检查实体集合不能为空
  9.         if (entitys == null || entitys.Count < 1)
  10.         {
  11.             throw new Exception("需转换的集合为空");
  12.         }
  13.         //取出第一个实体的所有Propertie
  14.         Type entityType = entitys[0].GetType();
  15.         PropertyInfo[] entityProperties = entityType.GetProperties();

  16.         //生成DataTable的structure
  17.         //生产代码中,应将生成的DataTable结构Cache起来,此处略
  18.         DataTable dt = new DataTable();
  19.         for (int i = 0; i < entityProperties.Length; i++)
  20.         {
  21.             //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
  22.             dt.Columns.Add(entityProperties[i].Name);
  23.         }
  24.         //将所有entity添加到DataTable中
  25.         foreach (object entity in entitys)
  26.         {
  27.             //检查所有的的实体都为同一类型
  28.             if (entity.GetType() != entityType)
  29.             {
  30.                 throw new Exception("要转换的集合元素类型不一致");
  31.             }
  32.             object[] entityValues = new object[entityProperties.Length];
  33.             for (int i = 0; i < entityProperties.Length; i++)
  34.             {
  35.                 entityValues[i] = entityProperties[i].GetValue(entity, null);
  36.             }
  37.             dt.Rows.Add(entityValues);
  38.         }
  39.         return dt;
  40.     }
复制代码


作者: 张兴康    时间: 2020-5-15 17:09

作者: 张兴康    时间: 2020-5-15 17:15





欢迎光临 度量快速开发平台-专业、快速的软件定制快开平台 (http://p.delit.cn/) Powered by Discuz! X3.2