Tuesday, 14 November 2017

Convert Object to DataTable in C#


Converting object to datatable using the C# code, it help in many places like doing the bulk insertion of data to database. There we need to send data in the form of table.
Suppose we have an Employee Class.

public class Employee
    {
        public int EmployeeId { get; set; }
        public string EName { get; set; }
        public int Age { get; set; }
        public decimal Salary { get; set; }
    }

Now instead of creating method for converting the object to datable, we will create a generic extension method which will convert any type of object into datatable.
public static class Utility

    {
        public static DataTable ToDataTable<T>(this List<T> obj)
        {
            Type t = obj[0].GetType();
            DataTable dt = new DataTable(t.Name);
            foreach (PropertyInfo pi in t.GetProperties())
            {
                dt.Columns.Add(new DataColumn(pi.Name));
            }
            foreach (var o in obj)
            {
                DataRow dr = dt.NewRow();
                foreach (DataColumn dc in dt.Columns)
                {
                    dr[dc.ColumnName] = o.GetType().GetProperty(dc.ColumnName).GetValue(o, null);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }

We have the collection of object for Employee class as like below.

// Creating object for employee Class
           List<Employee> emp = new List<Employee>()
            {
                new Employee(){ EmployeeId = 1, EName = "Bob", Age = 28, Salary = 5000 },
                new Employee(){ EmployeeId = 2, EName = "Rob", Age = 30, Salary = 5600 },
                new Employee(){ EmployeeId = 3, EName = "Ronny", Age = 31, Salary = 6000 },
            };


Now let’s use the extension method to see what we will get after using it.

DataTable dt = emp.ToDataTable<Employee>();




No comments:

Post a Comment

Others

You will like to read it