I found the below code on Stack Overflow. But I am not getting what fundamentally this code is doing. Can anyone please explain how this code works?
public static List<T> ToListof<T>(DataTable dt)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var objectProperties = typeof(T).GetProperties(flags);
var targetList = dt.AsEnumerable().Select(dataRow =>
{
var instanceOfT = Activator.CreateInstance<T>();
foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))
{
properties.SetValue(instanceOfT, dataRow[properties.Name], null);
}
return instanceOfT;
}).ToList();
return targetList;
}
Specifically, I would like to know where the columns' data are being typecast.
where coloumn's data is getting type casted<= It isn't, at least not in the code above. It is done by theSetValuemethod which takes anSystem.objectas parameter and all types eventually inherit fromSystem.objectproperties.SetValue(instanceOfT, dataRow[properties.Name], null);-dataRow[properties.Name]is the value from the cell, andSetValueputs it into the property