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();
}
想知道如何解释为什么会发生溢出异常?
最佳答案
逐步了解它。
- 复数是 hashtags 中的每个单词,它也有以 s 结尾的相同单词
- Hashtags 是除复数以外的所有单词。
要执行 2,您必须执行 1。但是,hashtags 不断变化,因此 plurals 试图不在原始集合上执行,而是在 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(plurals);
hashtags.Except(
hashtags.Except(plurals).Where(hashtag => { return hashtags.Contains($"{hashtag.ToUpper()}S"); })
.Select(h => $"{h.ToUpper()}S")
);
然后我们需要再次替换 plurals
.. 等等。
您的修复(添加 .ToList()
)是修复它的合乎逻辑的方法。
关于c# - IEnumerable 的多重枚举 - StackOverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477705/