从 List复制数据到数据表对象
我有一个列表<>对象(其中对象是自定义实体类),我有一个 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<> 获取数据到数据表中。
I have a a List<> of objects (where the objects are a custom entity class) and I have a DataTable which has columns that match the Properties of the Entity class.
Is there a way I can copy the data items with the List to the DataTable without having to loop through the List and manually adding the data to the DataTable.
Here's a sample of my current code (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);
}
}
Typically, the List<> will have around 27k items so I'm simply curious if there is a cleaner and/or more optimized way to get data from my List<> into a DataTable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如何使您的实体能够填充可以添加到数据表中的数据行。这样就可以减少反射的使用。
How about making your entities have ability to populate a data row which could be added to your data table. Thus way you reduce the usage of reflection.