很多时候需要将DataTable转换成一组model,直接对model执行操作会更加方便直观。
代码如下:
public static class DataTableToModel
{
public static List<T> ConvertToModel<T>(this DataTable dt)
{
if (dt == null || dt.Rows.Count == )
{
return null;
} var result = new List<T>(); var objType = typeof(T);
var properties = objType.GetProperties();
var columnNames = GetDataTableColumnNames(dt); foreach (DataRow dr in dt.Rows)
{
var obj = objType.Assembly.CreateInstance(objType.FullName);
//var obj = Activator.CreateInstance(objType);
foreach (var property in properties)
{
if (columnNames.Contains(property.Name))
{
var cellValue=dr[property.Name];
object propertyValue=cellValue; //非泛型
if (!property.PropertyType.IsGenericType)
{
propertyValue = cellValue == null ? null : Convert.ChangeType(cellValue, property.PropertyType);
}
else //泛型Nullable<>
{
Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
propertyValue = cellValue == null ? null : Convert.ChangeType(cellValue, Nullable.GetUnderlyingType(property.PropertyType));
}
} property.SetValue(obj, propertyValue, null);
}
} result.Add((T)obj);
} return result;
} private static HashSet<string> GetDataTableColumnNames(DataTable dt)
{
var columnNames = new HashSet<string>();
foreach (DataColumn column in dt.Columns)
{
columnNames.Add(column.ColumnName);
}
return columnNames;
}
}