C # use Aggregate,
Directly run the Code:
IEnumerable <int> list = Enumerable. Range (2, 10); int all = list. Aggregate (sum, index) => sum + index );
View Code
Debugging, the first call, found that sum and index respectively take the list of 1st and 2nd values:
F5 next, we found that the index was added to sum (sum + = index), then index took the next value, and accumulated to sum. Repeat this step until the value in the list is obtained:
The final calculation result is 65.
The other two overload functions:
Int all = list. Aggregate (10, (sum, index) => sum + index );
View Code
The 2nd parameters are the same as those in the previous example. The value of the cumulative list is the same as that of the previous example. The initial value of the 1st parameters must be applied to the cumulative value. In this example, the value is 10 plus 65, and the calculation result is 75.
Bool is75 = list. Aggregate (10, (sum, index) => sum + index, res => res = 75 );
View Code
1st 2nd parameters are the same as above. 3rd parameters are used to determine the cumulative result. Here, the cumulative result is 75 and the calculated result is true.
We can find that list. aggregate (sum, index) => sum + index) is actually list. the exception of Aggregate (0, (sum, index) => sum + index) is equivalent to the initial value of 0.