How to Convert DataTable to Generic List in C#

How to Convert DataTable to Generic List in C#

In this article, Sometimes we need to convert DataTable to generic List. Suppose we want to convert a DataTable (containing data of Employee table) to a generic List of custom data type Employee Model

Employee.cs

public class Employee
{
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public string EmpMobile { get; set; }
}

We will create two methods, the first method (CreateItemFromRow) will convert data row to class object and the second method (ToList) will maintain/generate a list of class objects converted by the first method.

private static T CreateItemFromRow<T>(DataRow row, List<PropertyInfo> properties) where T : new()
{
            T item = new T();
            foreach (var property in properties)
            {
                if (row.Table.Columns.Contains(property.Name))
                {
                    if (row[property.Name] != DBNull.Value)
                        property.SetValue(item, row[property.Name], null);
                }
            }
            return item;
}

public static List<T> ToList<T>(this DataTable table) where T : new()
{
            List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List<T> results = new List<T>();
 
            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                results.Add(item);
            }
            return results;
}
DataTable dtEmployee = GetEmployeeData();
List<Employee> lstEmployee = dtEmployee.ToList<Employee>();
.

2020-06-03