1

I need help with this code which doesn't work...

I want to change items from Array1, itemps position depending on Array2 items, where Array1 = Array0 and Array0 values are always changing.

Here is what I tried:

float[] Array0 = {1.524,2.345,3.12,4.55,5.345};
float[] Array1 = Array0;
int[] Array2 = {2,1,3};

foreach (int item in Array2)
    if(item!=0)
        Array1[item]=0;

Output :

Array1 = {1.524,0,0,0,5.345}

Do you have any solution ?

3
  • 1
    what is the expected output? Commented May 21, 2020 at 17:17
  • Arrays are reference types. So when you do float[] Array1 = Array2 you get a pointer to the same array in memory. So there is just 1 array with 2 pointers to it. Looks like you want Array1 to be a copy of Array0. Try float[] Array1 = Array0.ToArray(); Commented May 21, 2020 at 17:19
  • @Knoop I'd prefer float[] Array1 = (float[])Array0.Clone(); myself. Commented May 21, 2020 at 19:08

1 Answer 1

1

As mentionned in comments, you need to make a copy of array0 into array1 with Clone():

var array0 = new []{ 1.524, 2.345, 3.12, 4.55, 5.345 };
var array1 = (double[])array0.Clone();
int[] array2 = { 2, 1, 3 };

//change array0
array0[2] += 5;
array0[3] += 5;
array0[4] += 5;

foreach (var idx in array2.Where(idx => Math.Abs(array0[idx] - array1[idx]) > 1e-6))
    array1[idx] = 0;

Console.WriteLine(string.Join(" ", array1));

Result:

1.524 2.345 0 0 5.345
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.