Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a nested property with Linq

Tags:

c#

.net

linq

I Have a class that has a non-primitive property.
I need to update some child property of that property of parent class.

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

Now I need to update Pos in parentswhere Pos.Value == "2" ?

like image 204
eyalb Avatar asked Dec 31 '15 11:12

eyalb


1 Answers

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

If you need to update every items :

foreach (Parent parent in parents.Where(e => e.Pos.Value.Equals("2")))
    parent.Pos.Value = "new value";

If you need to update the first item only :

parents.FirstOrDefault(e => e.Pos.Value.Equals("2")).Pos.Value = "new value";
like image 84
Morgan M. Avatar answered Nov 03 '22 00:11

Morgan M.