How to Convert DataTable to Generic List in C#

June 28, 2018 // In: C#

Sometime we need to convert DataTable to generic List. Suppose we want to convert a DataTable (containing data of Employee table) to generic List of custom data type Employee (Employee Model).

We can achieve this by looping through rows of DataTable and add object of custom class to generic List.

For example, Consider a DataTable containing columns: EmployeeId, EmployeeName, EmployeeMobile

First of all, Create Custom Model Class of Employee

Employee.cs

Secondly, We’ll create an extension method instead of creating different methods for every class and custom data type to convert DataTable to generic List.

Concept will remain the same, we’ll loop through each row of datatable and assign value of each field of row to data members of model class.

We’ll create two methods, first method (CreateItemFromRow) will convert datarow to class object and second method (ToList) will maintain/generate list of class object converted by first method.

How to?

Lastly, we’ll call this extension method on DataTable object containing Employee table data.

 

Create DataTable From SQL Query in C#