62,074
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 将DataTable对象数据转为List泛型数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataTable"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dataTable)
{
if (dataTable == null) throw new ArgumentNullException("dataTable");
T template = Activator.CreateInstance<T>();
PropertyInfo[] pis = template.GetType().GetProperties();
if (pis == null || pis.Length <= 0) throw new CustomException(string.Format("类型{0}没有定义属性!", template.GetType()));
//获取属性列表
List<T> list = new List<T>();
foreach (DataRow dRow in dataTable.Rows)
{
T item = Activator.CreateInstance<T>();
foreach (PropertyInfo pi in pis)
{
string propertyName = pi.Name;
if (!dataTable.Columns.Contains(propertyName)) continue;
object propertyValue = dRow[propertyName];
pi.SetValue(item, propertyValue, null);
}
list.Add(item);
}
return list;
}