C#C
C#3y ago
345 replies
joren

✅ Deferred Execution or Forcing Immediate Execution

So I was reading the documentation on LINQ and I came across the two concepts i wrote in the title, now lets look at:

int[] nums = { 1, 2, 3, 4, 5};

var numQuery = from num in nums where (num % 2) != 0 select num;

foreach (int num in numQuery) { 
    Console.Write(num);
}


Now its pretty clear its deferred execution, we declare the query but its actually executed when the foreach is called. What I dont understand is why
var evenNumQuery =
    from num in numbers
    where (num % 2) == 0
    select num;

int evenNumCount = evenNumQuery.Count();


Is considered Immediate execution, it still declares it and then triggers the query, in this case a foreach internally but conceptually this is pretty much the same.

This though:
List<int> numQuery2 =
    (from num in numbers
     where (num % 2) == 0
     select num).ToList();

// or like this:
// numQuery3 is still an int[]

var numQuery3 =
    (from num in numbers
     where (num % 2) == 0
     select num).ToArray();


Calling .ToList or To.Array makes sense, you'd be executing the query in place and returning the result of the execution rather than saving the query to be executed later. Am I misinterpreting the documentation?
Was this page helpful?