【问题标题】:What is the best way to create datatable from multiple uneven list<T>?从多个不均匀列表 <T> 创建数据表的最佳方法是什么?
【发布时间】:2016-01-17 17:35:17
【问题描述】:

我有 4 个“列表”列表,其中包含不同类型的数据(文本),每个列表中的项目数也不相同。从这些列表创建数据表的最佳方法是什么?

例如

class A {
  public int id {get; set;}
  public string Name {get; set;}
  public string detailInfo {get; set;}
}

class B {
  public string info {get; set;}
}

class C {
  public string Code {get; set;}
}

class D {
  public int contact {get; set;}
  public int contact2 {get; set;}
  public Addr {get; set;}
}

class E {
  main() {
    IList<A> listA= new List<A>();
    IList<B> listB= new List<B>();
    IList<C> listC= new List<C>();
    IList<D> listC= new List<D>();
  }
}

那么从上面的 4 个列表中,创建数据表的最佳方法是什么? 注意:每个列表中的项目数可能会有所不同..

【问题讨论】:

  • 你说的是DataTable类吗?你想要每个列表都有一个DataTable 吗?还是一个DataTable 用于所有列表?你能解释一下为什么需要这个吗?

标签: c# .net list generics


【解决方案1】:

我会用反射定义列名,然后遍历列表中的记录以填充行。像这样的:

public DataTable GetDataTable<T>(List<T> list) where T : class
{
   DataTable table = new DataTable();
   var fields = typeof(T).GetFields();

   //Create Columns
   foreach(var field in fields)
   {
      DataColumn c = new DataColumn(field.Name, field.GetType());
      c.AllowDbNull = true;
      table.Columns.Add(c);
   }

   //Create rows
   foreach(T record in list)
   {
      DataRow row = table.NewRow();

      foreach(var field in fields)
      {
         //If it's null the cell will contain DbNull.Value
         if(field.GetValue(record) != null)
            row[field.Name] = field.GetValue(record);
      }

      table.Rows.Add(row);
   }

   return table;
}

这将为您提供一个数据表,其中 columnNames 是您的类的属性名,而行是列表中每条记录的值。如果您的属性之一为空,则数据表将包含 DbNull.Value

【讨论】:

    【解决方案2】:

    @Alexander 我设法使用以下代码填充所需的表:

    public static DataTable ToDataTable<T>(List<T> items)
    {
            DataTable dataTable = new DataTable(typeof(T).Name);
    
            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)`enter code here`;
            foreach (PropertyInfo prop in Props)
            {
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name);
            }
            foreach (T item in items)
            {
               var values = new object[Props.Length];
               for (int i = 0; i < Props.Length; i++)
               {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
               }
               dataTable.Rows.Add(values);
          }
          return dataTable;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 2010-10-10
      • 2019-10-26
      • 2019-06-11
      • 2014-07-30
      • 2021-03-04
      • 1970-01-01
      • 2010-10-19
      相关资源
      最近更新 更多