milandjukic88
milandjukic88

Reputation: 1115

One "simple" problem about building LINQ query drives me crazy

IEnumerable<char> query = "Not what you might expect";

query = query.Where(c=>c!='a');
query = query.Where(c=>c!='e');
query = query.Where(c=>c!='i');
query = query.Where(c=>c!='o');
query = query.Where(c=>c!='u');

foreach(char c in query) Console.Write(c);

Simple LINQ query building. My question is, why all this queries execute? Why not only the last one? How this is compiled, how program knows to return to query initialization? I hope you understand my question.

I Know this code works and it's intuitive, but what happens behind the scenes?

Upvotes: 0

Views: 82

Answers (1)

John Wu
John Wu

Reputation: 52280

If you were to write it this way, only the last query would execute:

IEnumerable<char> source = "Not what you might expect";

query = source.Where(c=>c!='a');
query = source.Where(c=>c!='e');
query = source.Where(c=>c!='i');
query = source.Where(c=>c!='o');
query = source.Where(c=>c!='u');

foreach(char c in query) Console.Write(c);

Only the last query executes because each line replaces the queries assigned above it.

Your example, on the other hand, is equivalent to this:

IEnumerable<char> source = "Not what you might expect";

query = source.Where(c=>c!='a').Where(c=>c!='e').Where(c=>c!='i').Where(c=>c!='o').Where(c=>c!='u');

foreach(char c in query) Console.Write(c);

In this example, each line appends to the queries assigned above it. So obviously all of the queries will execute.

Upvotes: 5

Related Questions