Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list into data table [duplicate]

Tags:

c#

asp.net

I have a data list with some property. I want to convert that list data into data table. How to convert a list into datable.

like image 214
user2660267 Avatar asked Aug 07 '13 10:08

user2660267


People also ask

How copy data from list to DataTable in C#?

Step 1: Create a console application and add the Student class with the properties as below. Step 2: In Main method, create a list of students as below. 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.

What is a DataTable in C#?

In the ADO.NET library, C# DataTable is a central object. It represents the database tables that provide a collection of rows and columns in grid form. There are different ways to create rows and columns in the DataTable.


1 Answers

Add this function and call it, it will convert List to DataTable.

public static 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)         {             //Defining type of data column gives proper data table              var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);             //Setting column names as Property names             dataTable.Columns.Add(prop.Name, type);         }         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);            }            dataTable.Rows.Add(values);       }       //put a breakpoint here and check datatable       return dataTable; } 
like image 100
Harshil Raval Avatar answered Sep 18 '22 18:09

Harshil Raval