c# - 嵌套查询的 StackOverflowException,小项目计数

标签 c# .net linq stack-overflow

我发现了一些标题相似的话题,但似乎都没有合适的答案。 有人提到 4.0 之前的 .NET 版本中的一个错误 - 我使用 4.0,所以这不应该是它。

考虑示例: 我正在尝试创建类 Part 的实例集合,它不属于类 PartGroup 的任何实例。

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

partColl 是实现属性 Groups 和 Parts 的类的实例,每个 IEnumerable<T> 其中 T 分别是 PartGroup 或 Part,内部实现为 List<T> 。 partColl.Parts 包含所有存在的部分。 Group 类具有属性 IEnumerable<Part> Parts ,列出对属于该组的部分的引用。

在我目前的程序中,有 27 个部分和 5 个元素没有重叠的组。 如果不是犯规的话,没有什么应该困扰堆栈的,尽管有二次复杂性。
当我运行它时,它会因 hasGroup 上的异常而崩溃。

我错过了什么?


编辑: 我在这里提出的抽象有一个小细节: IEnumerable PartGroup.Parts 与 PartCollection 的两个属性不同,它不受列表支持,它是一个具有私有(private)集的自动属性,在 c'tor 中使用传入的 IEenumerable 进行初始化。这个 IEnumerable 背后的实例也是一个列表,每个组都有一个自己的列表,所以我不确定到底发生了什么。

但是,异常消失了:还使用 List 类型的变量支持该属性,并在构造函数中分配给它:_list = parts.ToList(),其中 parts 为 IEnumerable<Parts>,作为参数传递给 ctor。我做 ToList 只是为了确保它真的是一个列表,而不是一些半生不熟的查询,但它应该,因为在我构建组的地方,在传递之前为每个组分配一个新列表......

剩下的问题仍然很有趣:发生了什么,为什么自动属性“导致”了异常? 我会根据要求发布更多详细信息,但现在需要一段时间。

最佳答案

这个小样本不会重现问题。

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

关于c# - 嵌套查询的 StackOverflowException,小项目计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495045/

相关文章:

c# - 设计师问题 + Entity Framework (WPF MVVM)

c# - C#获取网页源码的方法

c# - 带有长非 ASCII 名称的电子邮件附件

c# - 如何直接返回 ILookup(不使用 Dictionary->ILookup 转换器)

c# - WPF 中的 ContextMenu 太宽

c# - 如何将此查询写成 lambda 表达式?

c# - 提供静态文件的 .NET Core Nancy 应用程序

c# - Cassandra System.OutOfMemoryException,它是一个 Thrift 错误吗?

c# - 将空元素添加到列表

c# - 使用函数的 LINQ 查询中的 Where 子句