Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将C.net中的List转换为List_C#_Linq_List_Ado.net - Fatal编程技术网

C# 将C.net中的List转换为List

C# 将C.net中的List转换为List,c#,linq,list,ado.net,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(DataT

我有一个像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循环的情况下,我将该数据集转换为如下列表

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

但它不起作用。如何执行此操作?

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

如何将单个数据行转换为用户类型?您是否可以只写DataRow x=ent;?
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();