将对象集合List<ReturnData>转换为DataTable

使用PropertyInfo时需要引入命名空间:System.Reflection

//创建表

DataTable dtResult = new DataTable();

//创建对象集合

List<ReturnData> retList = new ReturnData();

//获取此对象的公共属性

PropertyInfo[] propertys = typeof(ReturnData).GetProperties();

//遍历对象的所有属性并且创建列名

foreach (PropertyInfo pi in propertys)
{
  // 判断此属性是否有Getter
  if (!pi.CanRead) continue;
  dtResult.Columns.Add(pi.Name, pi.PropertyType);
}

//循环遍历对象类表,给DataTable添加数据行
foreach (var item in retList)
{
  propertys = item.GetType().GetProperties();
  DataRow newRow = dtResult.NewRow();
  foreach (PropertyInfo pi in propertys)
  {
    if (!pi.CanRead) continue;
    newRow[pi.Name] = pi.GetValue(item, null);
  }
  dtResult.Rows.Add(newRow);
}
注:本文根据https://blog.51cto.com/13492397/2083194改写,如有侵权,请及时联系。

-------------------------------------------------------------------------------------------------------------------------------------

扫描二维码关注公众号,回复: 6675757 查看本文章

菜鸟一枚,本文只是方便个人日后学习并使用,文中如有错误,欢迎指点各位大佬指点!

猜你喜欢

转载自www.cnblogs.com/MonkeyDWang/p/11105919.html