0

C# newbie and confused as to why this isn't working.

Suppose I have an array of {1 , 2 , 3}.

How would I loop through this array to change the values by a set increment, for example if the increment is 1:

{1 , 2 , 3} becomes {2 , 3 , 4}

and if its 2 it becomes {3 , 4 , 5} etc.

Here is my attempt -

foreach (int i in ls)
{
int index = i + increment;
}
1
  • Use a for-loop: for(int i=0;i<ls.Length;i++){ls[i]+=increment;} Commented Dec 6, 2015 at 2:10

2 Answers 2

1

you were near to succeed, but you failed because you put the result of the increment into a temporary variable that then get resetted at every loop and didn't change your original array

moreover foreach isn't suited for this kind of operation because you need anyway an index to point to the right array element to edit, so a for is better

int increment = 1;
for (int i = 0; i < ls.Length; i++) {
   int newValue = ls[i] + increment;
   ls[i] = newValue;
}

I've created a fiddle you can test

https://dotnetfiddle.net/lkkLUv

note that i let more or less your try so that you can see the difference, but the loop can be shrunk to

for (int i = 0; i < ls.Length; i++) {
    ls[i] += increment;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Using your notation, the following should do it:

var newarr = ls.Select(w => w + increment);

Comments