我有一个具有非原始属性的类。
我需要更新父类属性的一些子属性。
public class Parent
{
public string Abc { get; set; }
public Childclass Pos { get; set; }
}
public class Childclass
{
public string Value { get; set; }
}
List<Parent> parents = new List<Parent>()
Parent p1 = new Parent();
p1.Pos.Value = "1";
parents.Add(p1);
Parent p2 = new Parent();
p2.Pos.Value = "2";
parents.Add(p2);
现在我需要更新 parentsPos.Value == "2"
中的 Pos
吗?
最佳答案
List<Parent> parents = new List<Parent>();
Parent p1 = new Parent();
p1.Pos = new Childclass() { Value = "1" };
parents.Add(p1);
Parent p2 = new Parent();
p2.Pos = new Childclass() { Value = "2" };
parents.Add(p2);
如果您需要更新每个项目:
foreach (Parent parent in parents.Where(e => e.Pos.Value.Equals("2")))
parent.Pos.Value = "new value";
如果您只需要更新第一项:
parents.FirstOrDefault(e => e.Pos.Value.Equals("2")).Pos.Value = "new value";
关于c# - 使用 Linq 更新嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546091/