How to use lambda expressions to calculate a sum in C#?

In C#, you can use lambda expressions to perform summation operations. Below is an example code that uses a lambda expression for summation.

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        // 使用lambda表达式求和
        int sum = numbers.Sum(x => x);

        Console.WriteLine("Sum: " + sum);
    }
}

In the example above, we used the Sum method and lambda expression to calculate the sum of all elements in an integer array. In the lambda expression, x => x means performing an operation on each element x and returning x itself.

bannerAds