How To Ideas | How To Articles | How To Tutorials


0

How To Get Sum Of Even Numbers In C#


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:

  1. Using LINQ

      var temp = from number in numbers
      where (number % 2) == 0
      select number;
      int sum = temp.Sum();

  2. Using Lambda Expression

      int sum = numbers.Where(a => a % 2 == 0).Sum();

  3. Using foreach loop

      int sum = 0;
      foreach (Int32 number in numbers)
      {
      if (number % 2 == 0)
      sum += number;
      }

  4. 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.

Download Source Code

image

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)
Filed in: C# Tags: , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Submit Comment



© 0248 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.