加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – IEnumerable的多个枚举 – StackOverflowException

发布时间:2020-12-15 23:31:57 所属栏目:百科 来源:网络整理
导读:IEnumerable和 Linq的一个有趣问题. static void Main(string[] args){ var subject = "#Accountancy #premier #Agile #Apache #automation #Automation #banking #Banking #bankIngs #AutoMation"; var hashtags = subject.Split('#').Select(hashtag = has
IEnumerable和 Linq的一个有趣问题.

static void Main(string[] args)
{
    var subject = "#Accountancy #premier #Agile #Apache #automation #Automation #banking #Banking #bankIngs #AutoMation";
    var hashtags = subject.Split('#').Select(hashtag => hashtag.Trim().ToUpper()).Distinct();

    var plurals = hashtags.Where((hashtag) =>
    {
        return hashtags.Contains($"{hashtag.ToUpper()}S");
    }).Select(h => $"{h.ToUpper()}S");      //.ToList(); (1) - will not break

    //filter hashtags
    hashtags = hashtags.Except(plurals);    //.ToList(); (2) - will not break

    //if iterate,would break with:
    //System.StackOverflowException was unhandled Message: An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
    foreach (var hashtag in hashtags)
    {
        Console.WriteLine(hashtag);
    }

    Console.Read();
}

好奇如何解释为什么会发生溢出异常?

解决方法

一步一步地走过去.

>复数是主题标签中的每个单词,其中也包含以s结尾的相同单词
> Hashtags是除复数之外的每个词.

要执行2,必须执行1.但是,hashtags会不断变化,因此复数不会尝试执行原始集合,而是2的结果(同样依赖于1的结果).

您的查询将尝试:

hashtags = hashtags.Except(plurals);

替换复数

hashtags = hashtags.Except(
            hashtags.Where(hashtag => { return hashtags.Contains($"{hashtag.ToUpper()}S"); })
                    .Select(h => $"{h.ToUpper()}S")
           );

但是hashtags是hashtags.Except(复数);

hashtags.Except(
            hashtags.Except(plurals).Where(hashtag => { return hashtags.Contains($"{hashtag.ToUpper()}S"); })
                    .Select(h => $"{h.ToUpper()}S")
           );

然后我们需要再次替换复数……等等.

您的修复(添加.ToList())是修复它的逻辑方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读