代码之家  ›  专栏  ›  技术社区  ›  stevehipwell

如何将一行值从二维数组复制到一维数组中?

  •  14
  • stevehipwell  · 技术社区  · 17 年前

    int [,] oGridCells;
    

    int iIndex = 5;
    for (int iLoop = 0; iLoop < iUpperBound; iLoop++)
    {
      //Get the value from the 2D array
      iValue = oGridCells[iIndex, iLoop];
    
      //Do something with iValue
    }
    

    在.NET中是否有方法将固定第一个索引处的值转换为单个维度数组(而不是通过循环值)?

    如果数组只循环一次,我怀疑它是否会加快代码的速度(很可能会使代码变慢)。但是如果数组被严重操纵,那么一维数组将比多维数组更有效。

    6 回复  |  直到 17 年前
        1
  •  35
  •   BlueMonkMN    17 年前

    int[,] oGridCells = {{1, 2}, {3, 4}};
    int[] oResult = new int[4];
    System.Buffer.BlockCopy(oGridCells, 0, oResult, 0, 16);
    

    您还可以通过提供正确的字节偏移量,从数组中选择性地复制一行。此示例复制3行二维阵列的中间行。

    int[,] oGridCells = {{1, 2}, {3, 4}, {5, 6}};
    int[] oResult = new int[2];
    System.Buffer.BlockCopy(oGridCells, 8, oResult, 0, 8);
    
        2
  •  3
  •   divisionby0    5 年前

    unsafe code . 完整示例,显示了两种方式,如下所示:

    public class MultiSingleUnsafe
    {
        public static unsafe void Main(String[] a)
        {
        int rowCount = 6;
        int iUpperBound = 10;
        int [,] oGridCells = new int[rowCount, iUpperBound];
    
        int iIndex = rowCount - 2; // Pick a row.
    
        for(int i = 0; i < iUpperBound; i++)
        {
            oGridCells[iIndex, i] = i;
        }
    
        for (int iLoop = 0; iLoop < iUpperBound; iLoop++)
        {
            //Get the value from the 2D array
            int iValue = oGridCells[iIndex, iLoop];
            Console.WriteLine("Multi-dim array access iValue: " + iValue);
            //Do something with iValue
        }
        
        fixed(int *lastRow = &(oGridCells[iIndex,0]))
        {   
            for (int iLoop = 0; iLoop < iUpperBound; iLoop++)
            {
            int iValue = lastRow[iLoop];
            Console.WriteLine("Pointer access iValue: " + iValue);
            }
        }
        }
    }
    

        3
  •  1
  •   Daren Thomas    17 年前

    如果可能的话,我会大吃一惊:我打赌 oGridCells[iIndex, iLoop] 只是一种缩写(在MSIL内部),用于 oGridCells[iIndex * iLoop]

        4
  •  1
  •   vgru    17 年前

    无法获取对每个数组的引用。但是,您可以使用 jagged array

        5
  •  1
  •   AnnaR    17 年前

    “但是如果数组被严重操纵,那么一维数组将比多维数组更有效。”

    去年夏天我做了一些分析,很惊讶地发现2D和1D阵列在性能上没有显著差异。

    我没有测试锯齿阵列的性能。

        6
  •  1
  •   Willy David Jr    9 年前

    您可以尝试以下方法:

     int[,] twoD = new int[2,2];
     twoD[0, 0] = 1;
     twoD[0, 1] = 2;
     twoD[1, 0] = 3;
     twoD[1, 1] = 4;
    
     int[] result = twoD.Cast<int>().Select(c => c).ToArray();
    

    1, 2, 3, 4