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:

### Like this:

Like Loading...

*Related*