List to Datatable Converter Using C#


In this article, I will describe to you how to convert a List objects to a DataTable.

Step 1: Create a console application and add the Student class with the properties as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Compare2Objects
    public class Program
        static void Main(string[] args)
    public class Student
        public string Name { get; set; }
        public int StudentId { get; set; }
        public int? Age { get; set; }

Step 2: In Main method, create a list of students as below.

List<Student> Students = new List<Student>(){
    new Student() { Name = "Jack", Age = 15, StudentId = 100 },
    new Student() { Name = "Smith", Age = 15, StudentId = 101 },          
    new Student() { Name = "Smit", Age = 15, StudentId = 102 }

Step 3: Now we are going to convert this list object to a DataTable. For that we need to create a new class and a conversion method as below.

public class ListtoDataTableConverter
    public DataTable ToDataTable<T>(List<T> items)
        DataTable dataTable = new DataTable(typeof(T).Name);
        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
            //Setting column names as Property names
        foreach (T item in items)
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
        //put a breakpoint here and check datatable
        return dataTable;

The above method will set the property name as a column name for the DataTable and for each object in the list; it will create a new row in the DataTable and insert values.

Step 4: Now create an instance of the above class and call the method with the list object from the Main method.

ListtoDataTableConverter converter = new ListtoDataTableConverter();
DataTable dt = converter.ToDataTable(Students);  

For the complete source code, please find the attached solution.