Monday, 3 April 2017

Convert List to Data Table Using C#

How to Convert List to Data Table Using C#

Here i am sharing how to convert list to data table using C#. I implemented a generic method for this and called to convert list to data table

Following are the generic method that i created using c#.

public static DataTable CreateDataTableFromList<T>(IEnumerable<T> listData)
            //here getting the of T object
            Type type = typeof(T);
            var properties = type.GetProperties();

            // Initializing datatable
            DataTable tableData = new DataTable();
            foreach (PropertyInfo info in properties)
            {         //dadding columns in "tableData" datatabe     
                tableData.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
            // adding values in datatable
            foreach (T entity in listData)
                object[] values = new object[properties.Length];
                for (int i = 0; i < properties.Length; i++)
                    values[i] = properties[i].GetValue(entity);

            //retuning the datatable
            return tableData;

Here, I am calling the "CreateDataTableFromList" method to convert list to datatable.

public ActionResult Test()
            IList<Student> studentList = new List<Student>() {
            new Student(){ ID=1, Name="Alok Singh",Age=32,Address="Delhi",DOB="18/01/1984"},
            new Student(){ ID=2, Name="Rahul Saini",Age=32,Address="Kolkatta",DOB="20/10/1984"},
            new Student(){ ID=3, Name="Ashok Pradhan",Age=40,Address="Dehradun",DOB="14/051974"},
            new Student(){ ID=4, Name="Sachin Kinra",Age=22,Address="Rajsthan",DOB="15/08/1995"},
            new Student(){ ID=5, Name="Deepak Mehta",Age=37,Address="Mohali",DOB="10/02/1980"},
            new Student(){ ID=6, Name="Manpreet Singh",Age=30,Address="Chandigarh",DOB="20/06/1986"}

            DataTable result = CreateDataTableFromList(studentList);

            return View(result);


No comments:

Post a Comment

Note: only a member of this blog may post a comment.