var sumOfRoots = numbers //IEnum0 .Where(x => x > 0) //IEnum1 .Select(x => Math.Sqrt(x)) //IEnum2 .Select(x => Math.Exp(x)) //IEnum3 .Sum();
例如,数字= { – 1,4,9}.
这是幕后发生的事情:
1.获得所有普查员(正面通行证)
> numbers调用GetEnumerator()返回(让我们用它来表示)IEnum0实例
> IEnum0调用GetEnumerator(),它返回IEnum1实例
> IEnum1调用GetEnumerator()返回IEnum2实例
> IEnum2调用GetEnumerator()返回IEnum3实例
2.调用MoveNext(向后传递)
> .Sum()在IEnum3上调用MoveNext()
> IEnum3在IEnum2上调用MoveNext()
> IEnum2在IEnum1上调用MoveNext()
> IEnum1在IEnum0上调用MoveNext()
3.从MoveNext返回(前后传球)
> IEnum0移动到元素-1并返回true.
> IEnum1检查-1是否满足条件(这不是真的)所以IEnum1在IEnum0上调用MoveNext().
> IEnum0移动到元素4并返回true.
> IEnum1检查4是否满足条件(为真)并返回true
> IEnum2什么都不做,只返回IEnum1的输出,这是真的
> IEnum2什么都不做,只返回IEnum2的输出,这是真的
4.呼叫当前(向后传球)
> .Sum()在IEnum3上调用Current.
> IEnum3在IEnum2上调用Current
> IEnum2在IEnum1上调用Current
> IEnum1在IEnum0上调用Current
5.回流(前进传球)
> IEnum0返回4
> IEnum1返回4
> IEnum2返回sqrt(4)= 2
> IEnum3返回exp(2)
6.重复步骤2.-5.直到第3步返回false
解决方法
static void Main(string[] args) { var numbers = new []{ -1,9 }; double sumOfRoots = numbers.Where(IsGreaterThanZero) .Select(ToSquareRoot) .Select(ToExp) .Sum(x => ToNumber(x)); Console.WriteLine($"sumOfRoots = {sumOfRoots}"); Console.Read(); } private static double ToNumber(double number) { Console.WriteLine($"SumNumber({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($"{number} > 0: {isGreater}"); return isGreater; }
输出:
-1 > 0: False
4 > 0: True
Math.Sqrt(4): 2
Math.Exp(2): 7.38905609893065
SumNumber(7.38905609893065)
9 > 0: True
Math.Sqrt(9): 3
Math.Exp(3): 20.0855369231877
SumNumber(20.0855369231877)
sumOfRoots = 27.4745930221183