Introduction
This blog explains how to convert a list into a DataTable.
List To Data Table
Step 1
Add Some Reference
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
This above reference is used to allow DataTable, PropertyDescriptor classes
Step 2
Create an ExtensionMethod Method
- public static class ExtensionMethod {
- public static DataTable ToDataTable < T > (this List < T > iList) {
- DataTable dataTable = new DataTable();
- PropertyDescriptorCollection propertyDescriptorCollection =
- TypeDescriptor.GetProperties(typeof(T));
- for (int i = 0; i < propertyDescriptorCollection.Count; i++) {
- PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
- Type type = propertyDescriptor.PropertyType;
-
- if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable < > ))
- type = Nullable.GetUnderlyingType(type);
- dataTable.Columns.Add(propertyDescriptor.Name, type);
- }
- object[] values = new object[propertyDescriptorCollection.Count];
- foreach(T iListItem in iList) {
- for (int i = 0; i < values.Length; i++) {
- values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
- }
- dataTable.Rows.Add(values);
- }
- return dataTable;
- }
- }
Step 3
I add sample code, as shown below
- public partial class Form1: Form {
- public Form1() {
- InitializeComponent();
- List < ad > obj = new List < ad > ();
- obj.Add(new ad {
- Name = "ss"
- });
- DataTable dt = obj.ToDataTable();
- }
- }
-
- internal class ad {
- public string Name {
- get;
- set;
- }
- }