LoginSignup
10
12

More than 5 years have passed since last update.

ListをDataTableに変換する

Posted at

忘れないように

sample.cs
public static DataTable ToDataTable<T>(this List<T> data)
    {
      var properties = TypeDescriptor.GetProperties(typeof(T));
      var table = new DataTable();
      foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
      foreach (T item in data)
      {
        var row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
          row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        table.Rows.Add(row);
      }
      return table;
    }
10
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
12