How To Ideas | How To Articles | How To Tutorials


0

How To Get Sum Of All Numbers In A List


You are storing data in a list and now wants to show the result as sum of all the numbers present in that list. This is really simple if you just wants to have sum of all the items present in your list but if you wants to get sum of not all but some elements of list then you can do this using just a simple iteration through your list.

Instructions:

If you just want to have sum of all the items present in your List, then just use the following statement.

list1.Sum();

If you want to have sum of selected items that follows similar structure say you want to have sum of those items which are larger than 10, then you have to use Lambda Expressions, try the following command

list1.Where(y => y > 10).Sum();

If you want to have sum of all the even numbers, then try the following code

list1..Where(y => y % 2 == 0).Sum();

If you want to have sum of items that are present on even index ( 0, 2, 4, etc.) then try the following code

int result = 0;
for (int j = 0; j < numbers.Count; j++,j++)
{
     result += numbers[j];
}

If you want to have sum of items that are present on odd index ( 1,3,5 etc.) then try the following code

int result = 0;
for (int j = 1; j < numbers.Count; j++,j++)
{
result += numbers[j];
}

Here is my full code with snapshot of the output in Console.

List<int> numbers = new List<int>();

numbers.Add(4);
numbers.Add(12);
numbers.Add(13);
numbers.Add(3);
numbers.Add(21);

 
Console.WriteLine("All The Numbers Present In List:");

foreach (var item in numbers)
{
    Console.WriteLine(item);
}

Console.WriteLine();

int result = numbers.Sum();
int result1 = numbers.Where(y => y > 10).Sum();
int result2 = numbers.Where(y => y % 2 == 0).Sum();
int result3 = 0;
int result4 = 0;

for (int j = 0; j < numbers.Count; j++,j++)
{
    result3 += numbers[j];
}

 
for (int j = 1; j < numbers.Count; j++, j++)
{
    result4 += numbers[j];
}

Console.WriteLine(String.Format("Simple Sum Is: {0}",result));
Console.WriteLine(String.Format("Sum Of Numbers Greater Than 10 is: {0}", result1));
Console.WriteLine(String.Format("Sum Of Even Numbers Is: {0}", result2));
Console.WriteLine(String.Format("Sum Of Numbers At Even Index Is: {0}", result3));
Console.WriteLine(String.Format("Sum Of Numbers At Odd Index Is: {0}", result4));

image

Incoming search terms:

  • c# sum of list of integers (1)
Filed in: C# Tags: , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Submit Comment



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