Introduction

This blog explains how to convert a list into a DataTable.

List To Data Table

Step 1
Add Some Reference
  1. using System.Collections.Generic;
  2. using System.ComponentModel;
  3. using System.Data;
This above reference is used to allow DataTable, PropertyDescriptor classes

Step 2
Create an ExtensionMethod Method
  1. public static class ExtensionMethod {
  2. public static DataTable ToDataTable < T > (this List < T > iList) {
  3. DataTable dataTable = new DataTable();
  4. PropertyDescriptorCollection propertyDescriptorCollection =
  5. TypeDescriptor.GetProperties(typeof(T));
  6. for (int i = 0; i < propertyDescriptorCollection.Count; i++) {
  7. PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
  8. Type type = propertyDescriptor.PropertyType;
  9. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable < > ))
  10. type = Nullable.GetUnderlyingType(type);
  11. dataTable.Columns.Add(propertyDescriptor.Name, type);
  12. }
  13. object[] values = new object[propertyDescriptorCollection.Count];
  14. foreach(T iListItem in iList) {
  15. for (int i = 0; i < values.Length; i++) {
  16. values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
  17. }
  18. dataTable.Rows.Add(values);
  19. }
  20. return dataTable;
  21. }
  22. }
Step 3
I add sample code, as shown below
  1. public partial class Form1: Form {
  2. public Form1() {
  3. InitializeComponent();
  4. List < ad > obj = new List < ad > ();
  5. obj.Add(new ad {
  6. Name = "ss"
  7. });
  8. DataTable dt = obj.ToDataTable();
  9. }
  10. }
  11. internal class ad {
  12. public string Name {
  13. get;
  14. set;
  15. }
  16. }
android