我正在获取用户详细信息列表并将一些详细信息存储到另一个列表中并返回该列表,但问题是最后它返回正确的行数但每行都有相同的值,这是最后一行的值
GetUserList usr = new GetUserList();
List<GetUserList> UsersList = new List<GetUserList>();
List<users> lstusers= usersBase.GetUsersListByOrgId(OrgId, null);
try
{
if (lstusers.Count > 0)
{
usr.Message = "Success";
for (int i = 0; i < lstusers.Count; i++)
{
usr.UserID = Convert.ToInt32(lstusers[i].userID);
usr.UserFirstName = Convert.ToString(lstusers[i].forename);
UsersList.Add(usr);
//return usr;
}
}
else
{
usr.Message = "Failed";
}
return UsersList;
}
catch (Exception e)
{
throw e;
}
答案 0 :(得分:5)
将usr
的声明/实例化移动到循环中:
for (int i = 0; i < lstusers.Count; i++)
{
GetUserList usr = new GetUserList();
usr.UserID = Convert.ToInt32(lstusers[i].userID);
usr.UserFirstName = Convert.ToString(lstusers[i].forename);
UsersList.Add(usr);
//return usr;
}
否则你一直在向GetUserList
的同一个实例添加列表引用,并覆盖其值 - 所以最终每行都有相同的值,即最后一行&#39; s值。
答案 1 :(得分:3)
你必须在for循环中实例化对象,目前同一个对象多次存储在列表中,改变你的代码如下:
for (int i = 0; i < lstusers.Count; i++)
{
GetUserList usr = new GetUserList(); // not this line
usr.Message = "Success";
usr.UserID = Convert.ToInt32(lstusers[i].userID);
usr.UserFirstName = Convert.ToString(lstusers[i].forename);
UsersList.Add(usr);
}
目前您每次都在修改同一个对象,因此结果将是所有列表项中最后更新的内容。
答案 2 :(得分:2)
因为您每次在循环迭代中更新同一用户并一次又一次地添加到列表中。 你应该每次在循环迭代中创建一个新用户
GetUserList usr ;
List<GetUserList> UsersList = new List<GetUserList>();
List<users> lstusers= usersBase.GetUsersListByOrgId(OrgId, null);
try
{
if (lstusers.Count > 0)
{
for (int i = 0; i < lstusers.Count; i++)
{
//create a new instance of user here
usr = new GetUserList();
usr.Message = "Success";
usr.UserID = Convert.ToInt32(lstusers[i].userID);
usr.UserFirstName = Convert.ToString(lstusers[i].forename);
UsersList.Add(usr);
//return usr;
}
}
else
{
usr.Message = "Failed";
}
return UsersList;
}
catch (Exception e)
{
throw e;
}
答案 3 :(得分:2)
每次使用新的用户对象
GetUserList usr =null;
List<GetUserList> UsersList = new List<GetUserList>();
List<users> lstusers= usersBase.GetUsersListByOrgId(OrgId, null);
try
{
if (lstusers.Count > 0)
{
// ;
for (int i = 0; i < lstusers.Count; i++)
{
usr= new GetUserList();
usr.Message = "Success"
usr.UserID = Convert.ToInt32(lstusers[i].userID);
usr.UserFirstName = Convert.ToString(lstusers[i].forename);
UsersList.Add(usr);
//return usr;
}
}
else
{
usr.Message = "Failed";
}
return UsersList;
}
catch (Exception e)
{
throw e;
}
答案 4 :(得分:1)
您正在将相同的GetUserList实例添加到列表中。在循环中,仅为GetUserList类的一个实例更新字段usr.UserID usr.UserFirstName。因此,效果是(假设lstusers.Count = 10),您将此对象添加10次到列表中。将GetUserList usr = new GetUserList();
移到循环内,并usr.Message =
。