Guest User

Untitled

a guest
Dec 13th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. public class MyClass
  2. {
  3. public uint ID { get; set; }
  4. public List<double> Values { get; set; }
  5. }
  6.  
  7. List<MyClass> objects = new List<MyClass>();
  8.  
  9. var query = objects.Select(o => new { o.ID, o.Values } ).ToList(); // this example returns only ID field
  10.  
  11. public DataTable ConvertToDataTable<T>(IList<T> data)
  12. {
  13. DataTable table = new DataTable();
  14. PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
  15.  
  16. foreach (PropertyDescriptor prop in properties)
  17. table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
  18.  
  19. foreach (T item in data)
  20. {
  21. DataRow row = table.NewRow();
  22.  
  23. foreach (PropertyDescriptor prop in properties)
  24. row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
  25.  
  26. table.Rows.Add(row);
  27. }
  28.  
  29. return table;
  30. }
Add Comment
Please, Sign In to add comment