我试图更新在C#中,看起来像这样使用Linq更新嵌套列表值?
名单<Users
>
嵌套列表 - 用户类型
- 列表<UserComponents
>
- - UserComponentKey
- - 计数
这里有一个书面例如:
用户列表: UserType = 1
UserComponents
- UserComponentKey = XYZ
- 计数= 3
用户类型= 2个
UserComponents
- UserComponentKey = XYZ
- 计数= 7
我需要更新UserComponentKey XYZ的用户类型2只,目前我更新已中断,并更新所有用户类型的XYZ。这是我当前的方法,它不工作,因为它们更新包含指定组件密钥的所有usertype的UserComponent计数值,而不是我所针对的特定usertype。
CLASSES:
public class Users
{
public string UserType { get; set; }
public List<UserComponent> UserComponents { get; set; }
}
public class UserComponent
{
public string UserComponentKey { get; set; }
public int Count { get; set; }
}
方法1:
Users.Where(us => us.UserType == "2")
.First().UserComponents
.Where(uc => uc.UserComponentKey == "XYZ")
.First().Count = value;
方法2:
if(users.UserType == "2")
{
foreach(var component in users.UserComponents)
{
switch(component.UserComponentKey)
{
case "XYZ":
component.Count = value;
break;
}
}
}
码生成LIST(类似): 列表UserComponents =新列表();
if (Item.UserAddOn != null)
{
for (var i = 0; i < Item.UserAddOn.First().Count; i++)
{
UserComponents.Add(new UserComponent
{
UserComponentKey = Item.UserAddOn[i].ComponentKey,
Count = 0
});
}
}
if (Item.User != null)
{
for (var i = 0; i < Item.User.First().Count; i++)
{
Users.Add(new User()
{
UserType = Item.User[i].ComponentKey,
Count = 0,
UsersComponents = UserComponents
});
}
}
我已经删除了实际值等,但希望有人能指出我在这里正确的方向。
谢谢!
你的代码是不安全的,但它应该工作。问题是什么? – Pluc
它们当前更新包含指定组件密钥的所有usertype的UserComponent计数值,而不是我指定的特定usertype。 – Dan
所以,如果我有4个usertypes,所有与组件键“J32S”所有四个将使用这些方法更新。 – Dan