I have a data tier select method that returns a datatable. It\'s called from a business tier method that should then return a strongly typed generic List.
What I wa
I know this answer is very late but i spent an hour and above to prepare this code because i needed this first then i thought some one in search of a solution for this question may get use of this..
Inorder for my answer to work correctly, you need to have same names for your list properties as in the DataBase table-columns(fields) or the DataTable column names.
Solution:
public List GetListFromDT(Type className, DataTable dataTable)
{
List list = new List();
foreach (DataRow row in dataTable.Rows)
{
object objClass = Activator.CreateInstance(className);
Type type = objClass.GetType();
foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = type.GetProperty(column.ColumnName);
prop.SetValue(objClass, row[column.ColumnName], null);
}
list.Add(objClass);
}
return list;
}
How to use ?
Lets say you have a values populated datatable named dtPersons
DataTable dtPersons; //populate this datatable
Then lets say you have a class with the following properties.
public class Persons{
public string Name {get; set;}
public int Age {get; set;}
}
Now pack and put the method in your model. call the method as below.
List dynamicListReturned = GetListFromDT(typeof(Persons), dataTable);
List listPersons = dynamicListReturned.Cast().ToList();
That's it now you got your list from the datatable in listPersons.
Remember: Both the names in the class properties and the DataTable/Database should be the same