#region 将DataTable转为List<>
/// <summary>
/// 将一个DataTable转为List
/// </summary>
/// <typeparam name="T">转向类型</typeparam>
/// <param name="dt">要转化的DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : new()
{
List<T> list = new List<T>();
for (int i = 0; i < dt.Rows.Count; i++)
{
T t = new T();
PropertyInfo[] properties = t.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
try
{
propertyInfo.SetValue(t, dt.Rows[i][propertyInfo.Name], null);
}
catch { }
}
list.Add(t);
}
dt.Dispose();
return list;
}
/// <summary>
/// 将一个DataTable转为List
/// </summary>
/// <typeparam name="T">转向类型</typeparam>
/// <param name="dt">要转化的DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : new()
{
List<T> list = new List<T>();
for (int i = 0; i < dt.Rows.Count; i++)
{
T t = new T();
PropertyInfo[] properties = t.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
try
{
propertyInfo.SetValue(t, dt.Rows[i][propertyInfo.Name], null);
}
catch { }
}
list.Add(t);
}
dt.Dispose();
return list;
}
#endregion
下午写的一个小方法,给大家分享一下。
调用:var list = DataTable.ToList<类>();
注意:必须写在静态类中