hidden
hidden

Reputation: 3236

How to edit a property that is deep within an object

Suppose there is a person object that has many ICollection and ObjectType2 has Icollection

So to edit a property you could theoretically search deep with forloops. But what would be a better way that is syntactically nice.

For example to edit a property called PP one could do the following:

foreach (var item in PersonData)
            {
                foreach (var item2 in item.Staffs)
                {
                    foreach (var item3 in item2.Employees)
                    {
                        foreach (var item4 in item3.EmployeePositions)
                        {
                            item4.PP = "test";
                        }
                    }
                }
            }

But I am looking for something much nice such as: Whether it via linq or whatever method.

Upvotes: 3

Views: 82

Answers (2)

Ian Mercer
Ian Mercer

Reputation: 39277

If these objects were stored in a database you would almost certainly do a query against the EmployeePositions table possibly filtering it by joining back against the Employees or Staff tables.

If you really need to access all instances of EmployeePositions you perhaps need a separate collection containing them rather than continually enumerating through the properties of other objects to find them.

Upvotes: 3

Dan Bryant
Dan Bryant

Reputation: 27515

var positions = PersonData
                .SelectMany(p => p.Staffs)
                .SelectMany(s => s.Employees)
                .SelectMany(e => e.EmployeePositions);
foreach (var position in positions)
{
   position.PP = "test";
}

This is the equivalent to the nested loops.

Upvotes: 6

Related Questions