剑弑 发表于 2018-8-9 15:27:46

DataTable转换成List集合2

/// <summary>
      /// 把Dt转换成实体集合
      /// </summary>
      /// <typeparam name="T">实体</typeparam>
      /// <param name="dt">表</param>
      /// <returns></returns>
      public List<T> DtOrList<T>(DataTable dt) where T : class, new()
      {
            try
            {
                List<T> list = new List<T>();
                string sStr = "";
                foreach (DataColumn item in dt.Columns)
                {
                  sStr += item.ColumnName.ToUpper() + ",";
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                  //============================== 创建实体实例并获取实例中的所有公共属性 =========================
                  T t = Activator.CreateInstance<T>();
                  PropertyInfo[] PrInfo = t.GetType().GetProperties();
                  // end========================== 创建实体实例并获取实例中的所有公共属性 =========================
                  foreach (PropertyInfo Info in PrInfo)
                  {
                        //====================== 当属性名称和列名相同时对实体字段进行赋值 ========================
                        if (sStr.Contains(Info.Name.ToUpper()))
                        {
                            if (dt.Rows != DBNull.Value)
                            {
                              /*此处加入类型判断及转换*/
                              Info.SetValue(t, dt.Rows, null);
                            }
                            else
                            {
                              Info.SetValue(t, null, null);
                            }
                            break;
                        }
                        // end================== 当属性名称和列名相同时对实体字段进行赋值 ========================
                  }
                  list.Add(t);
                }
                return list;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
      }

比之前的方法在性能进行了优化,降低了时间复杂度,提交了转换效率。。。


ibcadmin 发表于 2018-8-9 23:25:48

++++++
页: [1]
查看完整版本: DataTable转换成List集合2