find the sum of a list of numbers in csharp

There are several ways to find the sum of a list of numbers in C#. Here are two common methods:

Using a loop:

main.cs
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
int sum = 0;
foreach(int num in numbers)
{
    sum += num;
}
Console.WriteLine("The sum is: " + sum); // Output: The sum is: 15
183 chars
8 lines

Using LINQ:

main.cs
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
int sum = numbers.Sum();
Console.WriteLine("The sum is: " + sum); // Output: The sum is: 15
147 chars
4 lines

Both methods will give you the same result, but the LINQ method is more concise and can be easier to read for some people.

related categories

gistlibby LogSnag