linqlistgenericsdeferred-execution

Deferred execution of List<T> using Linq


Suppose I have a List<T> with 1000 items in it.

I'm then passing this to a method that filters this List. As it drops through the various cases (for example there could be 50), List<T> may have up to 50 various Linq Where() operations performed on it.

I'm interested in this running as quickly as possible. Therefore, I don't want this List<T> filtered each time a Where() is performed on it.

Essentially I need it to defer the actual manipulation of the List<T> until all the filters have been applied.

Is this done natively by the compiler? Or just when I call .ToList() on the IEnumerable that a List<T>.Where() returns, or should I perform the Where() operations on X (Where X = List.AsQueryable())?

Hope this makes sense.


Solution

  • Yes, deferred execution is supported natively. Every time you apply a query or lambda expression on your List the query stores all the expressions that is executed only when you call .ToList() on the Query.