public static List<T> DataTable2Entities<T>(DataTable table)
{
if (null == table || table.Rows.Count <= 0) return default(List<T>);
List<T> list = new List<T>();
List<string> keys = new List<string>();
foreach (DataColumn c in table.Columns)
{
keys.Add(c.ColumnName.ToLower());
}
for (int i = 0; i < table.Rows.Count; i++)
{
T entity = Activator.CreateInstance<T>();
PropertyInfo[] attrs = entity.GetType().GetProperties();
foreach (PropertyInfo p in attrs)
{
if (keys.Contains(p.Name.ToLower()))
{
if (!DBNull.Value.Equals(table.Rows[i][p.Name]))
{
p.SetValue(entity, Convert.ChangeType(table.Rows[i][p.Name], p.PropertyType), null);
}
}
}
list.Add(entity);
}
return list;
}
使用方法: var model=DataTable2Entities<Model.Article>(dt);
文章转载自: DataTable如何转换为实体类 http://www.studyofnet.com/news/1145.html