Интересная проблема с IEnumerable и Linq.Множественное перечисление IEnumerable - StackOverflowException
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' до полной итерации по ней. – wimh
Читайте о ** Linq и отложенном исполнении ** и объедините эти показания с двумя другими ответами. Затем вы увидите, почему ваш код ломается. Отсроченное исполнение может привести к некоторым ловушкам. – derpirscher