How To Convert a List Into a DataTable

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.   
  10.             if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable < > ))  
  11.                 type = Nullable.GetUnderlyingType(type);  
  12.             dataTable.Columns.Add(propertyDescriptor.Name, type);  
  13.         }  
  14.         object[] values = new object[propertyDescriptorCollection.Count];  
  15.         foreach(T iListItem in iList) {  
  16.             for (int i = 0; i < values.Length; i++) {  
  17.                 values[i] = propertyDescriptorCollection[i].GetValue(iListItem);  
  18.             }  
  19.             dataTable.Rows.Add(values);  
  20.         }  
  21.         return dataTable;  
  22.     }  
  23. }  
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.   
  12. internal class ad {  
  13.     public string Name {  
  14.         get;  
  15.         set;  
  16.     }  
  17. }  
android