/// <summary>
/// 将Datatable转换为泛型列表对象
/// </summary>
/// <typeparam name="T">泛型T的数据类型</typeparam>
/// <param name="dataTable">待转换的DataTable对象</param>
/// <returns>目标泛型列表对象</returns>
protected List<T> DataTableToList<T>(DataTable dataTable)
{
List<T> list = new List<T>();
Type targetType=typeof(T);
PropertyInfo[] allPropertyArray = targetType.GetProperties();
foreach (DataRow rowElement in dataTable.Rows)
{
T element=Activator.CreateInstance<T>();
foreach (DataColumn columnElement in dataTable.Columns)
{
foreach (PropertyInfo property in allPropertyArray)
{
if(property.Name.Equals(columnElement.ColumnName))
{
if (rowElement[columnElement.ColumnName] == DBNull.Value)
{
property.SetValue(element, null, null);
}
else
{
property.SetValue(element, rowElement[columnElement.ColumnName], null);
}
}
}
}
list.Add(element);
}
return list;
}
/// 将Datatable转换为泛型列表对象
/// </summary>
/// <typeparam name="T">泛型T的数据类型</typeparam>
/// <param name="dataTable">待转换的DataTable对象</param>
/// <returns>目标泛型列表对象</returns>
protected List<T> DataTableToList<T>(DataTable dataTable)
{
List<T> list = new List<T>();
Type targetType=typeof(T);
PropertyInfo[] allPropertyArray = targetType.GetProperties();
foreach (DataRow rowElement in dataTable.Rows)
{
T element=Activator.CreateInstance<T>();
foreach (DataColumn columnElement in dataTable.Columns)
{
foreach (PropertyInfo property in allPropertyArray)
{
if(property.Name.Equals(columnElement.ColumnName))
{
if (rowElement[columnElement.ColumnName] == DBNull.Value)
{
property.SetValue(element, null, null);
}
else
{
property.SetValue(element, rowElement[columnElement.ColumnName], null);
}
}
}
}
list.Add(element);
}
return list;
}