测试数据如下
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("Product", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("Version", Type.GetType("System.String"));
DataColumn dc3 = new DataColumn("Description", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
DataRow newRow;
newRow = dt.NewRow();
newRow["Product"] = "水果刀";
newRow["Version"] = "2.0";
newRow["Description"] = "打架专用";
dt.Rows.Add(newRow);
newRow = dt.NewRow();
newRow["Product"] = "折叠凳";
newRow["Version"] = "3.0";
newRow["Description"] = "行走江湖七武器之一";
dt.Rows.Add(newRow);
List<TestClass> list = CopyToList<TestClass>(dt);
测试数据中测试类如下
public class TestClass
{
public virtual string Product { get; set; }
public virtual string Version { get; set; }
public virtual string Description { get; set; }
}
公用方法如下
/// <summary>
/// 将DataTable中的数据拷贝到指定类型的list对象中
/// </summary>
/// <typeparam name="R">新对象类型</typeparam>
/// <param name="dt">数据表对象</param>
/// <returns></returns>
public static List<R> CopyToList<R>(DataTable dt)
where R : new()
{
//获取传泛型的具体属性
Type resultType = typeof(R);
List<R> listR = new List<R>(dt.Rows.Count);
R r;
DataColumn dataCol;
object value;
//获取类的具体属性及属性的数据类型
PropertyInfo[] propertyInfos = resultType.GetProperties();
int[] propertyValueIndex = new int[propertyInfos.Length];
int i, j;
DataRow dataRow;
for (j = 0; j < propertyInfos.Length; j++)
{
dataCol = dt.Columns[propertyInfos[j].Name];
propertyValueIndex[j] = dataCol == null ? -1 : dataCol.Ordinal;
}
for (i = 0; i < dt.Rows.Count; i++)
{
dataRow = dt.Rows[i];
r = new R();
for (j = 0; j < propertyInfos.Length; j++)
{
if (propertyValueIndex[j] != -1)
{
value = dataRow[propertyValueIndex[j]];
propertyInfos[j].SetValue(r, value is DBNull ? null : value);
}
}
listR.Add(r);
}
return listR;
}