Where not a subset, it is a filter. The difference lies at the heart of how LINQ works.
You can come up with Where , roughly speaking, keeping a reference to the original IEnumerable , as well as some code that checks the condition, and some state that tells how far it went. When you execute getNext() on the Where output, the code snippet passes through the source IEnumerable until it finds an element that satisfies the condition, then returns it (or reaches the end of the original IEnumerable , which means this is also at the end of Where ).
This is a lazy assessment - it considers only as many terms as necessary at any given time. Thus, the original IEnumerable must be present and not be modified in its entirety. If you call ToList() , the evaluation will be carried out immediately - all elements will be extracted and placed in the list before continuing.
The best reading material about this is C # and the god Link, John Skeet. His messages include reimplementing all of Linqβs core functions with a detailed discussion of implementation issues so you can see exactly how they (possibly) work.
Introduction
Part 2 - Where (!)
jwg Apr 30 '14 at 4:55 a.m. 2014-04-30 16:55
source share