如果多次调用,Concat会导致堆栈溢出 [英] Concat causes stack overflow if called multiple times

查看:75
本文介绍了如果多次调用,Concat会导致堆栈溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用程序意外崩溃并出现堆栈溢出错误.经过研究,我发现崩溃的原因是以下代码:

Application accidentally crashed with stack overflow error. After research I found that the reason of crash is following code:

foreach (var item in items)
{
    result = result.Concat(item.Data);
}

这是多个 IEnumerable 的串联.当 items 包含10,000个元素时,应用程序崩溃了.

This is concatenation of multiple IEnumerables. Application crashed when items contained 10,000 elements.

SelectMany 修复了此问题.但是还是...

SelectMany fixed this issue. But still...

为什么 Concat 扩展名在此处导致堆栈溢出?

Why Concat extension causes stack overflow here?

推荐答案

请记住, Concat 的结果不是集合-它是一个 query .

Remember that the result of Concat is not a collection - it's a query.

因此,您的结果"有效

Enumerable.Concat(item10000.Data, 
                  Enumerable.Concat(item9999.Data, 
                                  ....
                                    Enumerable.Concat(item2.Data, 
                                                      item1.Data))));

生成嵌套查询时,它会引起堆栈溢出.

When the nested queries are generated it causes a stack overflow.

另一种选择是创建列表并每次添加到列表中:

Another option would be to create a list and add to it each time:

var list = new List<something>();
foreach (var item in items)
{
    list.AddRange(item.Data);
}

基本上是 SelectMany 的工作(但使用延迟的枚举器,而不是 List ):

Which is essentially what SelectMany does (but with a deferred enumerator, not a List):

result = items.SelectMany(item => item.Data);

这篇关于如果多次调用,Concat会导致堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆