I have a Generic list of a class that I automatically convert it to DataTable using Reflection
and extension methods.Now I want to do it in reverse direction.I
Use AsEnumerable()
method to support LINQ:
private List<T> ConvertToList<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
pro.SetValue(objT, row[pro.Name]);
}
return objT;
}).ToList();
}
GetProperties
searches for the properties of the current Type, using the specified binding constraints.
The link in here: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx