DataTable to C# Class List Converter
Monday, December 25, 2017 Category : ASP.NET, ASP.NET MVC, C-sharp.NET 0
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
var value = row[prop.Name];
if (value == DBNull.Value)
{
value = null;
}
//propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
prop.SetValue(obj, value, null);
}
catch
{
continue;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}