Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4072552
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T16:53:58+00:00 2026-05-20T16:53:58+00:00

Below is a first attempt at using a Composite pattern. It works in the

  • 0

Below is a first attempt at using a Composite pattern.

It works in the sense that I can arbitrarily nest and get the correct results for the Duration property, with is the focus of the composition. BUT has a coding problem in that the iteration over the children needed to output the composite’s ToString() fails:

    System.InvalidOperationException : Collection was modified; enumeration operation may not execute.

The are a few extension methods for GetDescendents in this posting, including one that uses a stack to avoid the expense of recursion and
nested iterators.

I would like to understand the pattern better first though, so I have a few questions here:

  • How can I change the existing iteration code to prevent this error? I know how to convert it to a Linq equivalent but I want to leave it as the loops until I understand what is wrong with it.
  • Is it typical in the Composite to provide a Count property, or somehow cache the count after an iteration?
  • in the general case where you don’t need a specialized collection, would you typically have your Children property be IEnumerable, IList, or List?

Any good links for examples of working (non-trival) .net code would also be much appreciated.

Cheers,
Berryl

CODE

public interface IComponent    {
    void Adopt(IComponent node);
    void Orphan(IComponent node);

    TimeSpan Duration { get; }
    IEnumerable<IComponent> Children { get; }
}

public class Allocation : Entity, IAllocationNode    {

    public void Adopt(IAllocationNode node) { throw new InvalidOperationException(_getExceptionMessage("Adopt", this, node)); }
    public void Orphan(IAllocationNode node) { throw new InvalidOperationException(_getExceptionMessage("Orphan", this, node)); }

    public IEnumerable<IAllocationNode> Allocations { get { return Enumerable.Empty<IAllocationNode>(); } }

    public virtual TimeSpan Duration { get; set; }
}


class MyCompositeClass : IAllocationNode {
         public MyCompositeClass() { _children = new List<IAllocationNode>(); }

        public void Adopt(IAllocationNode node) { _children.Add(node); }
        public void Orphan(IAllocationNode node) { _children.Remove(node); }

        public TimeSpan Duration {
            get {
                return _children.Aggregate(TimeSpan.Zero, (current, child) => current + child.Duration);
            }
        }

        public IEnumerable<IAllocationNode> Children {
            get {
                var result = _children;
                foreach (var child in _children) {
                    var childOnes = child.Children;
                    foreach (var node in childOnes) {
                        result.Add(node);
                    }
                }
                return result;
            }
        }
       private readonly IList<IAllocationNode> _children;

        #endregion

        public override string ToString() {
            var count = Children.Count();
            var hours = Duration.TotalHours.ToString("F2");
            return string.Format("{0} allocations for {1} hours", count, hours);
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T16:53:59+00:00Added an answer on May 20, 2026 at 4:53 pm

    How can I change the existing
    iteration code to prevent this error?

    The exception is occurring because the code in the Children property’s getter is modifying a collection while iterating over it.

    You appear to be under the impression that the code

    var result = _children;
    

    creates a copy of the list referred to by the _children field. It does not, it just copies the reference to the list (which is what the value of the field represents) to the variable.

    An easy fix to copy the list over is to instead do:

    var result = _children.ToList();
    

    I know how to convert it to a Linq
    equivalent.

    The LINQ equivalent of your current code, which should work in a lazy manner, is:

    return _children.Concat(_children.SelectMany(child => child.Children));
    

    EDIT:
    I was originally under the impression that your code was limiting the traversal-depth to two levels (children and grandchildren), but now I can see that this is not the case: there is indeed a recursive call to the property Children rather than just the value of the field _children. This naming is quite confusing because the property and the ‘backing’ field represent different things entirely. I strongly recommend that you rename the property to something more meaningful, such as Descendants.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The first one is definitely something that works, but which one below is the
I first got an error usign the code below, explaining that DataGridLinkButton' must be
The example program below compiles two in-memory assemblies. The first compilation works fine. The
Below are two ways of reading in the commandline parameters. The first is the
When I attempt to overwrite an existing file, I get a permission denied error.
First off, I would like to say that I am just starting with PHP
Below I have a very simple example of what I'm trying to do. I
Below is my current char* to hex string function. I wrote it as an
Below is part of the XML which I am processing with PHP's XSLTProcessor :
Below is my $.ajax call, how do I put a selects (multiple) selected values

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.