We often return Data from SQL Server in DataTable Format and we would like to use that Datatable in code using List<object>. Below Function Converts provided Datatable into list easily. It is like an extension method to the DataTable and can be called directly to Convert it to a list.
public static List ConvertDataTable(this DataTable table) where T : new()
{
List list = new List();
var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new
{
PropertyInfo = propertyInfo,
Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType
}).ToList();
foreach (var row in table.Rows.Cast<DataRow>())
{
T obj = new T();
foreach (var typeProperty in typeProperties)
{
if (row.Table.Columns.Contains(typeProperty.PropertyInfo.Name))
{
object value = row[typeProperty.PropertyInfo.Name];
object safeValue = value == null || DBNull.Value.Equals(value)
? null
: Convert.ChangeType(value, typeProperty.Type);
typeProperty.PropertyInfo.SetValue(obj, safeValue, null);
}
}
list.Add(obj);
}
return list;
}
Visits: 418