2011-07-07 74 views
3

我有一個像UserEntity一類,如下轉換列表<DataRow>在C#.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; } 
} 

然後我填充的紀錄從數據庫table.and數據集則沒有foreach循環我轉換該數據集到列表如下

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爲文章

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

但它不起作用。我怎樣才能做到這一點?

+0

你會如何轉換一個DataRow到UserType?你會寫'DataRow x = ent'嗎? –

回答

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(); 
相關問題