星空网 > 软件开发 > ASP.net

.NET基础架构方法—DataTableToList通用方法

.NET架构基础方法—DataTableToList通用方法
 
我们经常需要将从数据库中所读取的数据以DataTable类型返回,也经常需要遍历DataTable转换为List>T<。我们也经常需要为每一个DataTable转换为List单独编写适合他们数据库架构地方法。下面上代码:
public static class DataTableTools<T> where T : class, new()  {    public static List<T> DataTableToList(DataTable dt)    {      List<T> list = null;      var rowCount = dt.Rows.Count;      if (rowCount > 0)      {        list = new List<T>();        int i;        for (i = 0; i < rowCount; i++)        {          T model = DataRowToModel(dt.Rows[i]);          list.Add(model);        }      }      return list;    }    private static T DataRowToModel(DataRow dr)    {      T model = new T();      var propertiesCount = typeof(T).GetProperties().Length;      for (int j = 0; j < propertiesCount; j++)      {        PropertyInfo propertyInfo = GetModelPropertyInfo(model, dr.Table.Columns[j]);        if (propertyInfo != null && dr[j] != DBNull.Value)        {          propertyInfo.SetValue(model, dr[j]);        }      }      return model;    }    private static PropertyInfo GetModelPropertyInfo(T model, DataColumn column)    {      string propertyName = column.ColumnName;      return model.GetType().GetProperty(propertyName);    }  }

 
代码中同样需要遍历DataTable,从而把DataTable中的每一行DataRow先转换为T类型的Model。在这里,我们根据每一行数据的数据架构来获取该行的每一列的ColumnName。我们也正是根据此ColumnName来获取泛型T的属性—GetModelPropertyInfo()方法,在其中通过SetValue设置该model的该属性值。也正是使用行数据架构的列属性名称来获取泛型T的属性,所以一定要保证泛型T的属性名称和数据架构名称相同,也只有这样才能使用该通用方法。
  
相信大牛们早已经掌握了这样的方法,如果有什么提议欢迎指出。如果你学会了,请为自己点赞,也是为我点赞。




原标题:.NET基础架构方法—DataTableToList通用方法

关键词:.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

亚马逊如何选品才能找到热销产品?:https://www.ikjzd.com/articles/112351
亚马逊选品:如何选择判断一款产品好不好卖?:https://www.ikjzd.com/articles/112352
日本站FBA仓库设置库存保管上限!接下来是...:https://www.ikjzd.com/articles/112353
写给新手卖家,亚马逊的生存模式!:https://www.ikjzd.com/articles/112354
2020年亚马逊选品新思维:https://www.ikjzd.com/articles/112355
亚马逊Listing怎么写?亚马逊Listing主要优化哪些?:https://www.ikjzd.com/articles/112356
6个技巧帮助你的谷歌搜索广告投放快速出单:https://www.kjdsnews.com/a/1840804.html
登顶女性类目第一,它靠生理裤营收上亿美金:https://www.kjdsnews.com/a/1840805.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流