Edit list inside foreach loop

I have an object with the following structure: (pseudocode)

class Client
{
- int ID
- int? ParentID
- string Name
- datetime CreateDate
- int ACClientID
- List <Client> Clients }

      

I want to iterate over the entire nested structure using a recursive foreach to set ACClientID ALL to a value.

I know that the enumerator in foreach is immutable, so the following doesn't work:

 private static bool AssignToChildren(ref ATBusiness.Objects.Client client, int ACClientID)
        {
            client.ACClientID = ACClientID;

            foreach (ATBusiness.Objects.Client child in client.Clients)
            {
                AssignToChildren(ref child, ACClientID);
            }
        }

      

What will be the most effective way to achieve my goal?

PS: I won't be adding or removing from the structure, just setting one attribute for each nested Client object.

[edit] I looked at What is the best way to modify a list in a foreach loop? but he doesn't give me the answer I need.

+2


source to share


4 answers


Since you never assign a parameter client

, you don't need to pass it using ref

.



Since you are not changing the object itself List<T>

, there is no reason why you cannot change the ACCClientID property even during enumeration. Its only, when you try to interfere with the list that is behind the enumeration, you will get an exception.

+11


source


    private static bool AssignToChildren(ATBusiness.Objects.Client client, int ACClientID)
    {
        client.ACClientID = ACClientID;

        foreach (ATBusiness.Objects.Client child in client.Clients)
        {
            AssignToChildren(child, ACClientID);
        }
    }

      



+1


source


May I suggest a specific property for this?

class Client
{
    public Client()
    {
        Clients = new List<Client>();
    }

    public List<Client> Clients { get; private set; }

    private int aCClientID;

    public int ACClientID
    {
        get { return aCClientID; }
        set { aCClientID = value; }
    }

    public int ACClientIDRecursive
    {
        get
        {
            return aCClientID;
        }
        set
        {
            aCClientID = value;
            foreach (var c in Clients)
            {
                c.ACClientIDRecursive = value;
            }
        }
    }
}

      

0


source


Try the following:

private static bool AssignToChildren(ref ATBusiness.Objects.Client client, int ACClientID)
{
  client.ACClientID = ACClientID;
  for (int i = client.Clients.Count - 1; i >= 0; i--) 
  {
    AssignToChildren(ref client.Clients[i], ACClientID);
  }
}

      

-2


source







All Articles