剑弑 发表于 2017-11-15 16:56:26

DataTable转换成List集合

/// <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>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                  //============================== 创建实体实例并获取实例中的所有公共属性 =========================
                  T t = Activator.CreateInstance<T>();
                  PropertyInfo[] PrInfo = t.GetType().GetProperties();
                  // end========================== 创建实体实例并获取实例中的所有公共属性 =========================
                  for (int j = 0; j < dt.Columns.Count; j++)
                  {
                        foreach (PropertyInfo Info in PrInfo)
                        {
                            //====================== 当属性名称和列名相同时对实体字段进行赋值 ========================
                            if (dt.Columns.ColumnName.ToUpper().Equals(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);
            }
      }
此方法转换性能并不是最优的,有兴趣的可以尝试着进行优化
如想要更优的方法,请留言:lol

ibcadmin 发表于 2017-11-15 22:46:18

{:2_31:}好久没看到教程了。。

剑弑 发表于 2017-11-16 08:56:38

ibcadmin 发表于 2017-11-15 22:46
好久没看到教程了。。

:lol

菜鸟一只 发表于 2018-1-24 13:11:46

大神,总结的很好,学习,谢谢

xzp132706 发表于 2018-3-20 11:55:29

xie

xzp132706 发表于 2018-3-20 11:55:47

:)

job_zhang 发表于 2018-4-16 10:43:50

ttt

剑弑 发表于 2018-5-14 15:22:00

job_zhang 发表于 2018-4-16 10:43
ttt

????

菜鸟一只 发表于 2018-11-12 14:01:43

谢谢,大佬分享
页: [1]
查看完整版本: DataTable转换成List集合