LINQ execution flow (homework)

The same statement can be written as follows:

var ints = new int[] { 2, 4, 1, 10, 3, 7 };

var x = ints
    .Where(c =>
        {
            Console.WriteLine($"1 Where for number: {c}");
            return c / 3 > 0;
        }) //< --(1)
    .Select(s2 => s2 + ints
        .Where(c =>
        {
            Console.WriteLine($"2 Where for number: {c}");
            return c / 3 == 0;
        }) // < --(2)
        .Aggregate((f, s) =>
        {
            Console.WriteLine($"Aggregate: f: {f} s: {s}");
            return f - s;
        }))
    .Sum();

In this every shorthand lambda expression can be written as a complete anonymous method with a method body. You just need to use the { .. } parentheses. Inside them you can write multiple statements. If you check the documentation for Where you can see that it expects (in your case) a Func<int, bool> as input parameter. That means that you pass an int inside and return a bool. This is why you need to write the explicit return statement as I did: return c / 3 > 0;

If you now insert there a debug output to the console you will get a written proof and insight into the execution of the entire code compartment.

The resulting output looks like the following:

1 Where for number: 2 1 Where for number: 4 2 Where for number: 2 2 Where for number: 4 2 Where for number: 1 Aggregate: f: 2 s: 1 2 Where for number: 10 2 Where for number: 3 2 Where for number: 7 1 Where for number: 1 1 Where for number: 10 2 Where for number: 2 2 Where for number: 4 2 Where for number: 1 Aggregate: f: 2 s: 1 2 Where for number: 10 2 Where for number: 3 2 Where for number: 7 1 Where for number: 3 2 Where for number: 2 2 Where for number: 4 2 Where for number: 1 Aggregate: f: 2 s: 1 2 Where for number: 10 .... ....


ints
    .Where(c => c / 3 == 0)     // (2,1)
    .Aggregate((f, s) => f - s) //  2-1

evaluates to 1

Therefore your query can be switched to:

var ints = new int[] { 2, 4, 1, 10, 3, 7 };

var x = ints
    .Where(c => c / 3 > 0) // (4,10,3,7)
    .Select(s2 => s2 + 1)  // (5,11,4,8)
    .Sum();                // 28

Tags:

C#

Linq