Click here to Skip to main content
15,897,518 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm trying to create a foreach loop that puts the all the integer values of an existing list in to an int, how would I go about this?

Thanks

What I have tried:

I've looked around but haven't really found a solution, I'm very new to programming.
Posted
Updated 20-Oct-21 2:10am
Comments
BillWoodruff 20-Oct-21 16:26pm    
Describe exactly what you want to end up with: a lis of integers ? or ?

We can't read your mind.

1 solution

Assuming you mean summing together the values of the integers in the list, then you'd just declare an integer variable and increment it by the values of each element:
C#
List<int> numbers = { 1, 2, 3, 4, 5 };
int result = 0;

foreach (int number in numbers)
{
  result += number;
}

However you can achieve this even easier using the Sum() method:
C#
List<int> numbers = { 1, 2, 3, 4, 5 };
int result = numbers.Sum(number => number);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900