Methods to Convert datatable to List

Suppose we have a datatable as following
DataTable dtEmp = new DataTable("Employee");
dtEmp.Columns.Add("EmpId", typeof(Int32));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Designation", typeof(string));
dtEmp.Columns.Add("DOJ", typeof(DateTime));
dtEmp.Columns.Add("Salary", typeof(decimal));    

and Employee class as below
public class Employee
    public int EmpId { get; set; }
    public string EmpName { get; set; }
    public string Designation { get; set; } 
    public DateTime DOJJ { get; set; } 
    public decimal Salary { get; set; }

Now we can convert the above DataTable into a List<Employee> using the below methods

Using a Loop

 List<Employee> EmployeeList = new List<Employee>();  
 for (int i = 0; i < dt.Rows.Count; i++) 
        Employee emp = new Employee(); 
        emp.EmpId = Convert .ToInt32 (dtEmp.Rows[i]["EmpId"]); 
        emp.EmpName = dtEmp.Rows[i]["EmpName"].ToString(); 
        emp.Designation = dtEmp.Rows[i]["Designation"].ToString(); 
        emp.DOJ = Convert.ToDateTime(dtEmp.Rows[i]["DOJ"]); 
        emp.Salary = Convert.ToDecimal(dtEmp.Rows[i]["Salary"]); 

Using LINQ
 List<Employee> EmployeeList = new List<Employee>();   
 EmployeeList = (from DataRow dr in dtEmp.Rows 
      select new Employee() 
                EmpId = Convert .ToInt32 (dr["EmpId"]), 
                EmpName = dr["EmpName"].ToString(),
                Designation = dr["Designation"].ToString();  
                DOJ = Convert.ToDateTime(dr["DOJ"]), 
                Salary = Convert.ToDecimal(dr["Salary"])

The above two methods are not the generic methods. We have to write the same code again if we need to convert Other data table (e.g Student table) . The following is a generic method that will convert any type of DataTable to a List.

Generic Method
Following methods are generic methods which will take datatable and user defined class as inputs and will return the List of class with the table data.
private static List ConvertToDataTable(DataTable dt)  
    List data = new List();  
    foreach (DataRow row in dt.Rows) 
        T item = GetItem(row);  
    return data; 
private static T GetItem(DataRow dr)  
    Type temp = typeof(T); 
    T obj = Activator.CreateInstance();  
    foreach (DataColumn column in dr.Table.Columns) 
        foreach (PropertyInfo pro in temp.GetProperties()) 
            if (pro.Name == column.ColumnName) 
                pro.SetValue(obj, dr[column.ColumnName], null); 
    return obj; 
List<Employee> EmployeeList = new List<Employee>();
EmployeeList = ConvertToDataTable<Employee>(dtEmp);  
Note: The DataTable Structure and the List Class Strucute should be Same


    Blogger Comment
    Facebook Comment


Post a Comment