Convert generic List/Enumerable to DataTable?

后端 未结 27 2122
臣服心动
臣服心动 2020-11-21 23:20

I have few methods that returns different Generic Lists.

Exists in .net any class static method or whatever to convert any list into a datatable? The only thing tha

27条回答
  •  囚心锁ツ
    2020-11-22 00:07

    This is a simple mix of the solutions. It work with Nullable types.

    public static DataTable ToDataTable(this IList list)
    {
      PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
      DataTable table = new DataTable();
      for (int i = 0; i < props.Count; i++)
      {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
      }
      object[] values = new object[props.Count];
      foreach (T item in list)
      {
        for (int i = 0; i < values.Length; i++)
          values[i] = props[i].GetValue(item) ?? DBNull.Value;
        table.Rows.Add(values);
      }
      return table;
    }
    

提交回复
热议问题