/// <summary>
/// DataTable转换为List
/// </summary>
public static IList<T> DataTable2List<T>(DataTable dt)
{
IList<T> list = new List<T>();
Type type = typeof(T);
string piName = "";
foreach (DataRow dr in dt.Rows)
{
T t = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
piName = pi.Name;
if (dt.Columns.Contains(piName))
{
if (!pi.CanWrite)
continue;
object value = dr[piName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
else
pi.SetValue(t, null, null);
}
}
list.Add(t);
}
return list;
}
/// DataTable转换为List
/// </summary>
public static IList<T> DataTable2List<T>(DataTable dt)
{
IList<T> list = new List<T>();
Type type = typeof(T);
string piName = "";
foreach (DataRow dr in dt.Rows)
{
T t = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
piName = pi.Name;
if (dt.Columns.Contains(piName))
{
if (!pi.CanWrite)
continue;
object value = dr[piName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
else
pi.SetValue(t, null, null);
}
}
list.Add(t);
}
return list;
}
本文介绍了一种将DataTable转换为泛型List<T>的方法,适用于.NET开发中数据操作的需求。该方法通过反射机制实现类型转换,能有效地将数据表中的数据映射到指定类型的对象集合。
435

被折叠的 条评论
为什么被折叠?



