我有一个List<>对象(对象是自定义实体类)和我有一个DataTable,其中的列与实体类的属性相匹配。
有没有办法可以将带有List的数据项复制到DataTable,而无需遍历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);
}
}
通常,列表&lt;&gt;将有大约27k项目,所以我只是好奇是否有更清洁和/或更优化的方式从我的列表中获取数据&lt;&gt;进入DataTable。
答案 0 :(得分:0)
如何让您的实体能够填充可以添加到数据表中的数据行。这样就减少了反射的使用。
答案 1 :(得分:-1)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for UserBO
/// </summary>
public class UserBO
{
public UserBO()
{
//
// TODO: Add constructor logic here
//
}
private string _mUserName;
public string UserName
{
get { return _mUserName; }
set { _mUserName = value; }
}
private string _mPassword;
public string Password
{
get { return _mPassword; }
set { _mPassword = value; }
}
private int _mUserID;
public int UserID
{
get { return _mUserID; }
set { _mUserID = value; }
}
}
IList<UserBO> objlistUserBo = new List<UserBO>();
objlistUserBo = objUserFacade.Getuserinfo(objUSerBO);
for (int iterator=0; iterator < objlistUserBo.Count; iterator++)
{
objUSerBO = (UserBO)objlistUserBo[iterator];
string name = objUSerBO.UserName;
string pwd = objUSerBO.Password;
}