StackOverflowException on a nested query, counting small items

I found several threads with similar headers, but they do not have a suitable answer. One mentioned an error in .NET versions prior to 4.0 - I use 4.0, so it should not be.

Consider an example: I am trying to create a collection of instances of the Part class that do not belong to any instance of the PartGroup class.

Func<Part,bool> hasGroup = P => partColl.Groups.Any( G => G.Parts.Contains(P) );
var groupless = partColl.Parts.Where( P => ! hasGroup(P) );

partColl is an instance of a class that implements the properties of groups and parts, each IEnumerable<T>where T is PartGroup or Part, respectively, internally implemented as List<T>. partColl.Parts contains all existing parts. class Group has the property of IEnumerable<Part> Partslisting references to parts belonging to the group.

In my current program there are 27 parts and 5 groups without overlapping elements. Nothing that should disturb the stack, despite the quadratic complexity, if something was not a foul.
When I run this, it will crash with the specified exception in hasGroup.

What am I missing?


EDIT: A small detail cited my abstraction presented here: IEnumerable PartGroup.Parts was, unlike the two PartCollection properties not supported by the list, it was a private-set auto-property initialized in c'tor with the IEenumerable passed in. The instance behind this IEnumerable is also a list and its own for each group, so I'm not sure what exactly is happening.

, : List , : _list = parts.ToList(), parts IEnumerable<Parts>, ctor. ToList , , , - , , , , , , ...

: , - "" ? , .

+4
1

.

using System;
using System.Linq;
using System.Collections.Generic;
class P
{
    class PartGroup
    {
        public List<Part> Parts { get; private set; }
        public PartGroup()
        {
            Parts = new List<Part>();
        }
    }

    class Part
    {
    }

    class PartCollection
    {
        public List<Part> Parts { get; set; }
        public List<PartGroup> Groups { get; set; }
        public PartCollection()
        {
            Parts = new List<Part>();
            Groups = new List<PartGroup>();
        }
    }

    static void Main()
    {
        var groups = new List<PartGroup> { new PartGroup(), new PartGroup(), new PartGroup(), new PartGroup(), new PartGroup() };
        var partColl = new PartCollection();
        partColl.Parts.Add(new Part());
        partColl.Groups.AddRange(groups);
        for (int i = 0; i < 27; i++)
        {
            var part = new Part();
            groups[i % groups.Count].Parts.Add(part);
            partColl.Parts.Add(part);
        }
        partColl.Parts.Add(new Part());

        Func<Part, bool> hasGroup = P => partColl.Groups.Any(G => G.Parts.Contains(P));
        var groupless = partColl.Parts.Where(P => !hasGroup(P)).ToList();
    }
}
0

All Articles