开发者

convert List<DataRow> to List<UserEntity> in C#.net

I have a class like UserEntity as below

[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; }
}

Then I populated a record as dataset from Db table.and then without foreach loop i convert that dataset to List as below

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();

Now I want开发者_StackOverflow社区 to convert lstRows to List as below by using the ConvertAll method:

  lstUsers=lstRows.ToList().ConvertAll(new Converter(ent=>ent));

But it doesn't work. How can I do this?


You need to manually map the DataRow fields to the fields of your UserEntity class. Something like this should work (untested):

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();

And, in fact, you don't need lstRows, nor do you need to initialize lstUsers to an empty list:

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜