Posted By

sekihin on 05/09/11


Tagged

c#


Versions (?)

convert a Generic List into DataTable


 / Published in: C#
 

URL: http://stackoverflow.com/questions/564366/generic-list-to-datatable

  1. // remove "this" if not on C# 3.0 / .NET 3.5
  2. public static DataTable ToDataTable<T>(this IList<T> data)
  3. {
  4. PropertyDescriptorCollection props =
  5. TypeDescriptor.GetProperties(typeof(T));
  6. DataTable table = new DataTable();
  7. for(int i = 0 ; i < props.Count ; i++)
  8. {
  9. PropertyDescriptor prop = props[i];
  10. table.Columns.Add(prop.Name, prop.PropertyType);
  11. }
  12. object[] values = new object[props.Count];
  13. foreach (T item in data)
  14. {
  15. for (int i = 0; i < values.Length; i++)
  16. {
  17. values[i] = props[i].GetValue(item);
  18. }
  19. table.Rows.Add(values);
  20. }
  21. return table;
  22. }

Report this snippet  

You need to login to post a comment.