How to convert list of object types to DataTable in C#?
Step 1: Create a Console Application and add the Student class with the properties shown below. Step 2 – In the main method, create a list of students as shown below. }; Step 3: Now we are going to convert this list object to a DataTable.
Table of Contents
How to assign DataTable to a class object in C#?
Suppose the name of the class is CommonMethod in which this method exists.
- public static class CommonMethod {
- public static list < T > ConvertToList < T > (DataTable dt) {
- var columnNames = dt.Columns.Cast < DataColumn > ().Select(c => c.ColumnName.ToLower()).ToList();
- var properties = type of(T).GetProperties();
How to bind a DataTable to a List in MVC?
The following are the two functions where if we pass a DataTable and a user defined class, it will return the List of that class with the DataTable data. List
What is column mapping in C#?
SqlBulkCopyColumnMapping(String, Int32) Creates a new column mapping, using a column name to refer to the source column and a column ordinal for the destination column. SqlBulkCopyColumnMapping(String, String) Creates a new column mapping, using column names to refer to the source and destination columns.
Can we convert DataTable to a list in C#?
Convert DataTable to List using a generic method. This is a generic method that will convert any type of DataTable to a list (the structure of the data table and the class structure of the list must be the same). The following are the two functions where we pass a DataTable and a user-defined class.
How to convert DataTable to list in C#?
Then we can convert Datatable from above class to List using these methods: Above method has reflection, therefore it is slower than other methods.
How to convert a DataTable to a generic list?
DataTable.Select() does not return the rows in the order they were present in the data table. If order is important, I feel like iterating over the collection of rows of data and forming a List is the right way to go or you could also use the overload of DataTable.Select(string filter expression, string sort).
How to change DT value of DataTable?
Change the student class name and dt value as per your requirements. In this case, the DataTable column name and the class property name must be the same; otherwise this function will not work properly. Download the source code for clarification.
How to add data to a list in C#?
Add the data values in the same order as they appear in your class; make sure to update it when you add properties. The reflection version is still there, so you can do it either way.