Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy one 2D array to another 2D array

Tags:

I used this code to copy one 2D array to another 2D array:

Array.Copy(teamPerformance, 0,tempPerformance,0, teamPerformance.Length); 

However, when I change some data in tempPerformance then these changes also apply to teamPerformance.
What should I do to control that?

like image 641
user2079550 Avatar asked Mar 31 '13 02:03

user2079550


People also ask

How do I copy one 2D array to another?

Copying Arrays Using arraycopy() method src - source array you want to copy. srcPos - starting position (index) in the source array. dest - destination array where elements will be copied from the source. destPos - starting position (index) in the destination array.


2 Answers

You need Clone()

double[,] arr =  {    {1, 2},    {3, 4} }; double[,] copy = arr.Clone() as double[,]; copy[0, 0] = 2; //it really copies the values, not a shallow copy,  //after: //arr[0,0] will be 1 //copy[0,0] will be 2 
like image 191
Sergey Kulgan Avatar answered Sep 19 '22 12:09

Sergey Kulgan


This is correct: Array.Copy performs a shallow copy, so the instances of arrays inside the inner dimension get copied by reference. You can use LINQ to make a copy, like this:

var copy2d = orig2d.Select(a => a.ToArray()).ToArray(); 

Here is a demo on ideone.

like image 45
Sergey Kalinichenko Avatar answered Sep 19 '22 12:09

Sergey Kalinichenko