In this article, I will talk about different method which we can use to get sum of only even numbers from a collection of number. Say if we have a List of integers and it has some random integers but we want to have sum of only even numbers or odd numbers, then you can use any of the following method. We will use the LINQ , Lambda expression, Foreach loop For loop to get only those numbers which we want and get sum of those numbers numbers.
Instructions:
- Using LINQ
var temp = from number in numbers
where (number % 2) == 0
select number;
int sum = temp.Sum(); - Using Lambda Expression
int sum = numbers.Where(a => a % 2 == 0).Sum(); - Using foreach loop
int sum = 0;
foreach (Int32 number in numbers)
{
if (number % 2 == 0)
sum += number;
} - Using for loop
int sum = 0;
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] % 2 == 0)
sum += numbers[i];
}
Here is snapshot of the Console window and you can download the Project from the link given below.
Incoming search terms:
- lambda expression for even number calculations c# (1)
- lamda expression sum (1)
- to find even programs using c and c sharp programming (1)
- write a program to check if the no is even or odd in asp net with c# (1)