Posted By

sekihin on 05/09/11


Tagged

datatable c#


Versions (?)

convert a DataTable into a generic list


 / Published in: C#
 

  1. public static class DataTableExtensions
  2. {
  3. public static IList<T> ToList<T>(this DataTable table) where T : new()
  4. {
  5. IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
  6. IList<T> result = new List<T>();
  7.  
  8. foreach (var row in table.Rows)
  9. {
  10. var item = CreateItemFromRow<T>((DataRow)row, properties);
  11. result.Add(item);
  12. }
  13.  
  14. return result;
  15. }
  16.  
  17. private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
  18. {
  19. T item = new T();
  20. foreach (var property in properties)
  21. {
  22. property.SetValue(item, row[property.Name], null);
  23. }
  24. return item;
  25. }
  26. }
  27.  
  28. Dim gList As New List(Of Guid)
  29. gList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))

Report this snippet  

You need to login to post a comment.