How to copy DataTable row to Object in C#?

.net, c#

Solution

For that exact purpose I am using this method below, datatable columns and type properties should have same names.

public static List<T> TableToList<T>(DataTable table)
{
  List<T> rez = new List<T>();
  foreach (DataRow rw in table.Rows)
  {
    T item = Activator.CreateInstance<T>();
    foreach (DataColumn cl in table.Columns)
    {
      PropertyInfo pi = typeof(T).GetProperty(cl.ColumnName);

      if (pi != null && rw[cl] != DBNull.Value)
      {
        var propType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
        pi.SetValue(item, Convert.ChangeType(rw[cl], propType), new object[0]);
      }

    }
    rez.Add(item);
  }
  return rez;
}

Problem

For example, I have an object of class: ``` class MyClass { public int a { get; set; } public string b { get; set; } public DateTime c { get; set; } } ``` And I have a DataTable object with columns with same names as in a MyClass. Is there a fast/simple way to copy each row of DataTable object to a MyClass object. Like this (but in my case i have too much columns): ``` for (int x = 0; x < dataTableObj.Rows.Count; x++) { myClassObj[x].a = dataTableObj.Rows[x]["a"]; myClassObj[x].b = dataTableObj.Rows[x]["b"]; myClassObj[x].c = dataTableObj.Rows[x]["c"]; } ``` Thank U.

Original source