将List <datarow>转换为C#.net </userentity> </datarow>中的List <userentity>

时间:2011-07-07 11:02:39

标签: c# linq list ado.net

我有一个像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));

但它不起作用。我怎么能这样做?

1 个答案:

答案 0 :(得分:7)

您需要手动将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();