Will more objects be created or will the C # compiler emit code similar to a nested loop with if inside?
Other objects; each LINQ operation ( SelectMany , Where , Select , etc.) will lead to the creation of a new place owner object that represents the pending IEnumerable<T> request for this operation, and then, when it finally repeats, each of them will result to an instance of an enumerator along with context, etc. In addition, there is a context with a captured variable for raised orderStorageId , etc.
Note that regular foreach will also lead to an instance of the enumerator, but foreach has the advantage that it can also use numbered enumerations, which means that for things like List<T> , the struct is actually used, not the class enumerator . And, of course, using a local variable ( orderStorageId ) directly (and not by an anonymous method) means that it does not need to be raised to a state / context object.
So, the original foreach more direct and efficient. An interesting question: is the difference important? Sometimes it is, sometimes it is not.
source share