convert List<DataRow> to List<UserEntity> in C#.
本文关键字:gt lt List in UserEntity DataRow convert to | 更新日期: 2023-09-27 18:01:21
我有一个类似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();
并且,事实上,您不需要lstrow,也不需要将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();