1:第一种例子:
/// <summary>
/// 用户名循环赋值
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public List<Users> FenPeiFillModelUsers(DataTable dt)
{
if (dt.Rows.Count == 0 || dt == null)
{
return null;
}
List<Users> Users = new List<Users>();
foreach (DataRow dr in dt.Rows)
{
Users beiBu = new Users();
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
PropertyInfo info = beiBu.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
if (info != null && dr[i] != DBNull.Value)
{
info.SetValue(beiBu, dr[i], null);
}
}
Users.Add(beiBu);
}
return Users;
}
2: 第二种万能的方法,使用了泛型方法
/// <summary>
/// DataTable转List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataTable"></param>
/// <returns></returns>
private List<T> FillModel<T>(DataTable dataTable) where T : new()
{
if (dataTable == null || dataTable.Rows.Count == 0)
{
return null;
}
var dataList = new List<T>();
foreach (DataRow row in dataTable.Rows)
{
var dataItem = new T();
foreach (DataColumn column in dataTable.Columns)
{
var property = typeof(T).GetProperty(column.ColumnName);
if (property != null && row[column] != DBNull.Value)
{
property.SetValue(dataItem, Convert.ChangeType(row[column], property.PropertyType));
}
}
dataList.Add(dataItem);
}
return dataList;
}