【发布时间】:2011-07-21 23:11:53
【问题描述】:
我有一个对象列表(其中对象是自定义实体类),我有一个 DataTable,其中包含与实体类的属性匹配的列。
有没有一种方法可以将列表中的数据项复制到数据表中,而无需遍历列表并手动将数据添加到数据表中。
这是我当前代码的示例(C# 4.0):
void MergeData()
{
List<MyEntity> myEntities = GetEntities();
// Create a DataTable based on the Properties of the MyEntity class
Type entity = typeof(MyEntity);
PropertyInfo[] properties = entity.GetProperties();
DataTable dt = new DataTable();
foreach (PropertyInfo pi in properties)
{
dt.Columns.Add(pi.Name);
}
// Here's where I loop through the List and fill the DataTable.
// Is there a way to fill the DataTable without looping through the List?
foreach (MyEntity e in myEntities)
{
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in properties)
{
dr[pi.Name] = pi.GetValue(e, null);
}
dt.Rows.Add(dr);
}
}
通常,List 将包含大约 27k 项,所以我只是想知道是否有更清洁和/或更优化的方式将数据从我的 List 获取到 DataTable。
【问题讨论】:
标签: c#-4.0 merge datatable generic-list