Reusing IEnumerable <T> produces a false result, for example. on. Any()

I got a little lost in the delayed execution:

I declare an instance of the IEnumerable implementation class

var wordEnumerable = new WordEnumerable(_text);

Then I repeat it (the first word is "Lorem")

foreach (var word in wordEnumerable)
                    Console.WriteLine(word);

.. which is written to the console.

Now right in the code i'm doing

Console.WriteLine(wordEnumerable.Any(w => w == "Lorem"));

.. and get the output False.

Now, if I put the .Any (..) part over the foreach loop, I get true, however the loop starts with the second word.

I expected .Net to create different runtime contexts for each call to IEnumerable and its main IEnumerator so that they do not interfere ... I would not want .Reset () manually to get the correct result?

What am I missing here?

Update

.. IEnumerable, .

+3
1

- Any GetEnumerator, IEnumerator<T>. , IEnumerable<T>. , WordEnumerable . :)

, :

Console.WriteLine("First");
foreach (var word in wordEnumerable)
{
    Console.WriteLine(word);
}

Console.WriteLine("Second");
foreach (var word in wordEnumerable)
{
    Console.WriteLine(word);
}

? , , WordEnumerable IEnumerable<string>, IEnumerable<object>, == .

+3

Source: https://habr.com/ru/post/1790449/


All Articles