Here is my c# code
Employee objEmp = new Employee();
List empList = new List();
foreach (DataRow dr in ds.Tables[0].Rows)
{
Here's extension method to convert DataTable to object list:
public static class Extensions
{
public static List ToList(this DataTable table) where T : new()
{
IList properties = typeof(T).GetProperties().ToList();
List result = new List();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow(DataRow row, IList properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (property.PropertyType == typeof(System.DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item,day,null);
}
else
{
if(row[property.Name] == DBNull.Value)
property.SetValue(item, null, null);
else
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
}
usage:
List lst = ds.Tables[0].ToList();
@itay.b
CODE EXPLAINED:
We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.
The property values are picked from the row's matching column cell.
PS: class property name and table column names must be same