Copy one 2D array to another 2D array

后端 未结 3 772
庸人自扰
庸人自扰 2020-12-09 16:44

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

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

Howeve

相关标签:
3条回答
  • 2020-12-09 17:11

    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
    
    0 讨论(0)
  • 2020-12-09 17:20

    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.

    0 讨论(0)
  • 2020-12-09 17:37

    According to MS(http://msdn.microsoft.com/en-us/library/z50k9bft.aspx):

    If sourceArray and destinationArray are both reference-type arrays or are both arrays of type Object, a shallow copy is performed. A shallow copy of an Array is a new Array containing references to the same elements as the original Array. The elements themselves or anything referenced by the elements are not copied. In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.

    0 讨论(0)
提交回复
热议问题