📜  c# sum of list - C# (1)

📅  最后修改于: 2023-12-03 14:39:44.186000             🧑  作者: Mango

C# Sum of List

In C#, calculating the sum of a list of numbers is a common task. In this guide, we will explore various ways to accomplish this task.

Method 1: Using a Loop

One way to calculate the sum of a list of numbers in C# is to use a loop. Here is an example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int sum = 0;

foreach (int number in numbers)
{
    sum += number;
}

Console.WriteLine(sum); // Output should be 15

In this example, we define a list of numbers and initialize a variable called sum to 0. We then iterate through each number in the list and add it to sum. Finally, we print out the value of sum.

Method 2: Using LINQ

Another way to calculate the sum of a list of numbers in C# is to use LINQ. Here is an example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int sum = numbers.Sum();

Console.WriteLine(sum); // Output should be 15

In this example, we define a list of numbers and then call the Sum method on the list. This method calculates the sum of all the elements in the list and returns the result. We then print out the value of sum.

Conclusion

Calculating the sum of a list of numbers is a common task in C#. We can accomplish this task using a loop or by using LINQ. The choice of method depends on personal preference and the specific requirements of the task.