C# IEnumerable-StackOverflowException的多重枚举
一个关于IEnumerable和Linq的有趣问题C# IEnumerable-StackOverflowException的多重枚举,c#,linq,deferred-execution,C#,Linq,Deferred Execution,一个关于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.T
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(尚未计算)重新分配给另一个计算,这将导致一个无限循环。如果将第二个求值放在另一个变量中,它将起作用:
var hashtags2 = hashtags.Except(plurals);
foreach (var hashtag in hashtags2)
{
Console.WriteLine(hashtag);
}
一步一步走过去
hashtags = hashtags.Except(plurals);
替换复数
hashtags = hashtags.Except(
hashtags.Where(hashtag => { return hashtags.Contains($"{hashtag.ToUpper()}S"); })
.Select(h => $"{h.ToUpper()}S")
);
但是hashtags
是hashtags.Except(复数)代码>
然后我们需要再次替换复数。。等等
您的修复(添加.ToList()
)是修复它的合乎逻辑的方法。在完全迭代之前,在过滤器中使用一个新变量以避免更改hashtags
。阅读有关Linq和延迟执行的内容,并将此读数与其他两个答案结合起来。然后,您将了解代码为何会中断。延迟执行可能会导致一些陷阱。我认为这不是完整的答案-hashtags=hashtags。除了(hashtags.Where(h=>h.StartsWith(“B”))代码>不会引发堆栈溢出异常。
hashtags.Except(
hashtags.Except(plurals).Where(hashtag => { return hashtags.Contains($"{hashtag.ToUpper()}S"); })
.Select(h => $"{h.ToUpper()}S")
);