📜  c# array.reduce - C# (1)

📅  最后修改于: 2023-12-03 15:13:48.563000             🧑  作者: Mango

C# Array.Reduce

Array.Reduce() is a built-in function in C# that allows you to apply a function to each element in an array and then accumulate the results of each operation into a single value. It works by taking in a callback function and an initial value, and then iterating through each element of the array.

Syntax
Array.Reduce<T>(T[] array, Func<T, T, T> callback, T initialValue)
  • T[] array: the array to reduce.
  • Func<T, T, T> callback: the function to apply to each element in the array. It takes two arguments: the current element and the accumulator value. It should return the new accumulator value.
  • T initialValue: the initial value of the accumulator.
Example
int[] nums = {1, 2, 3, 4, 5};
int sum = Array.Reduce(nums, (acc, curr) => acc + curr, 0);
Console.WriteLine(sum); // Output: 15

In this example, we have an array of integers nums with values from 1 to 5. We use the Reduce() function to accumulate the total sum of the values in the array. We pass in the callback function (acc, curr) => acc + curr to add each current value to the accumulator. We also pass in an initial value of 0 for the accumulator.

The result of the function call is 15, which is the sum of all the values in the nums array.

Notes
  • The callback function should be associative, meaning that the order that the elements are processed should not affect the final result.
  • If the array is empty, the Reduce() function will throw an exception.
  • There is also an overload of the Reduce() function that allows you to pass in an array of objects, and a lambda expression that selects the property to be used as the key for the accumulator.