我有一个像UserEntity这样的类,如下所示
[Serializable]
[XmlRootAttribute(ElementName = "UsersEntity", IsNullable = false)]
public class UserEntity
{
[XmlElement(DataType="string",ElementName="UsersID")]
public int UsersID { get; set; }
[XmlElement(DataType = "string", ElementName = "UserName")]
public string UserName { get; set; }
[XmlElement(DataType = "string", ElementName = "Password")]
public string Password { get; set; }
}
然后我从Db表中填充了一条记录作为数据集,然后在没有foreach循环的情况下将该数据集转换为List如下
Dataset _ods= new Dataset();
//create a list of UerEntity class
List<UserEntity> lstUsers=new List<UserEntity>();
// populate record as dataset from DB table
_ods = populateEmpData();
// convert List<DataRow> from Dataset withou Foreach Loop
List<DataRow> lstRows = _ods.Tables[0].AsEnumerable().ToList();
现在,我想使用ConvertAll方法将lstRows转换为List,如下所示:
lstUsers=lstRows.ToList().ConvertAll(new Converter(ent=>ent));
但这是行不通的。我怎样才能做到这一点?
最佳答案
您需要手动将DataRow字段映射到UserEntity类的字段。这样的事情应该起作用(未经测试):
lstUsers = (from dr in lstRows
select new UserEntity
{
UsersId = dr.Field<int>("user_id"),
UserName = dr.Field<string>("user_name"),
Password = dr.Field<string>("password")
}).ToList();
而且,实际上,您不需要lstRows,也不需要将lstUsers初始化为空列表:
var lstUsers = (from dr in _ods.Tables[0].AsEnumerable()
select new UserEntity
{
UsersId = dr.Field<int>("user_id"),
UserName = dr.Field<string>("user_name"),
Password = dr.Field<string>("password")
}).ToList();