You are yielding objects which have queries inside - it's not some sequence of array
values - its iterator objects which are not executed when you are passing them to constructor of MyType
. When you create list of MyType
objects
var result = GenerateCollection().ToList();
all MyType
instances are yielded and saved into list, but if you haven't executed iterators in MyType
constructor, then queries are not executed. And even more - they will be executed each time again, if you'll call some operator which executes query, e.g.
result[i].ArrayIterator.Count(); // first execution
foreach(var item in result[i].ArrayIterator) // second execution
// ...
You can fix it if you'll pass result of query execution to MyType
constructor:
yield return new MyType("a", array.Where(x => !x.Sublist.Contains('a')).ToList())
Now you are passing list of items instead of iterator (you can use ToArray()
) also. Query is executed when you are yielding MyType
instance, and it will not be executed again.