Convert a DataTable to Generic List Collection

Step 1: Since we need to create a List<T>, define an instance and in this list we need to add our custom type T.

Step 2: For each row we need to add the custom type T to our generic list so for each row of the DataTable I am doing that and for fetching the custom type, I used a separate function GetItem<T>.

Step 3: In the GetType<T> function I am using reflection to fetch the properties of the custom type passed and am comparing the same with column names present in the DataTable since these columns will act as properties of each type.
  1. private static List<T> ConvertDataTable<T>(DataTable dt)  
  2. {  
  3.    List<T> data = newList<T>();  
  4.    foreach (DataRowrow in dt.Rows)  
  5.    {  
  6.       Titem = GetItem<T>(row);  
  7.       data.Add(item);  
  8.    }  
  9.    return data;  
  10. }  
  11.   
  12. private static TGetItem<T>(DataRow dr)  
  13. {  
  14.    Type temp = typeof(T);  
  15.    T obj =Activator.CreateInstance<T>();  
  16.    foreach (DataColumncolumn in dr.Table.Columns)  
  17.    {  
  18.       foreach (PropertyInfopro in temp.GetProperties())  
  19.       {  
  20.          if (pro.Name == column.ColumnName)  
  21.          pro.SetValue(obj,dr[column.ColumnName], null);  
  22.          else  
  23.          continue;  
  24.       }  
  25.    }  
  26.    return obj;  
  27. }