Understanding LINQ method execution order


This is my answer to an interesting question asked yesterday on StackOverflow – what is the execution order of a LINQ query such as:

    var numbers = new[] { -1, 4, 9 };

    var sumOfRoots = numbers.Where(x => x > 0)
                            .Select(x => Math.Sqrt(x))
                            .Select(x => Math.Exp(x))
                            .Sum();

A quick an easy solution is to refactor the code in order to use custom delegates for each chained method (Where, Select and Sum), which makes things easier to debug. In this case I’m just printing a simple message to the console:

    static void Main(string[] args)
    {
        var numbers = new[] { -1, 4, 9 };

        double sum = numbers.Where(IsGreaterThanZero)
                            .Select(ToSquareRoot)       
                            .Select(ToExp)              
                            .Sum(x => ToNumber(x));

        Console.WriteLine($"{Environment.NewLine}Total = {sum}");

        Console.Read();
    }

    private static double ToNumber(double number)
    {
        Console.WriteLine($"ToNumber({number})");

        return number;
    }

    private static double ToSquareRoot(int number)
    {
        double value =  Math.Sqrt(number);

        Console.WriteLine($"Math.Sqrt({number}): {value}");

        return value;
    }

    private static double ToExp(double number)
    {
        double value =  Math.Exp(number);

        Console.WriteLine($"Math.Exp({number}): {value}");

        return value;
    }

    private static bool IsGreaterThanZero(int number)
    {
        bool isGreater = number > 0;

        Console.WriteLine($"{Environment.NewLine}{number} > 0: {isGreater}");

        return isGreater;
    }

The output is the following:
linq-order-output

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.