转换列表< D​​ataRow的>列出< UserEntity>在C#.NET

转换列表< D​​ataRow的>列出< UserEntity>在C#.NET

问题描述:

我有一类像UserEntity如下

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

然后,我填写了创纪录的数据集从数据库table.and再没有foreach循环我转换的数据集清单,如下列

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

现在我想转换lstRows列出如下使用ConvertAll方法:

Now I want 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?

您需要手动映射的DataRow字段您UserEntity类的字段。这样的事情应该工作(未经测试):

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

和,其实,你并不需要lstRows,也不需要初始化lstUsers一个空列表:

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