EN
C# / .NET - sum first n integers from List
0 points
In this article, we would like to show you how to sum first n integers from List in C#.
Quick solution:
xxxxxxxxxx
1
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
2
3
int n = 3;
4
5
int sum = numbers.Take(n).Sum(); // 6
In this example, we use Take()
method to take first 3
values from numbers array, then we use Sum()
method to get sum of them.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
10
int n = 3;
11
12
int sum = numbers.Take(n).Sum();
13
14
Console.WriteLine(sum);
15
}
16
}
Output:
xxxxxxxxxx
1
6