【问题标题】:Delete elements from 2d array c# [duplicate]从二维数组c#中删除元素[重复]
【发布时间】:2020-03-23 12:20:53
【问题描述】:

如何从二维数组中删除整行?我想继续从数组 shipPosition 中删除 1 行,直到它没有任何元素。

shipPosition -= shipPosition[0,0] 

shipPosition -= shipPosition[0,1]

例如

int[,] shipPosition = new int[3, 2];

shipPosition[0, 0] = 2;
shipPosition[0, 1] = 3;
shipPosition[1, 0] = 4;
shipPosition[1, 1] = 5;
shipPosition[2, 0] = 6;
shipPosition[2, 1] = 7;

【问题讨论】:

标签: c# arrays


【解决方案1】:

在 C# 中,数组(无论维度)是固定大小的。您可以更改元素的内容,但不能添加或删除元素(以及行)。

您需要编写(或从第三方找到)一个类来为您管理这个(很像List<T> 有效地允许更改一维数组中的元素数量)。

【讨论】:

    【解决方案2】:

    我建议更改集合的 typeList<int[]> (list of arrays) 而不是 2d array

      List<int[]> shipPosition = new List<int[]>() {
        new int[] {2, 3}, // 1st line 
        new int[] {4, 5}, // 2nd line 
        new int[] {6, 7}, // ...  
      };  
    

    现在,如果你想删除 enrire 行(比如最上面的一行,{2, 3}),就这样做吧

     shipPosition.RemoveAt(0);
    

    【讨论】:

      【解决方案3】:

      使用for 循环的方法

      public static int[,] DeleteRow(int rowDeleteIndex, int[,] sourceArray)
      {
          int rows = sourceArray.GetLength(0);
          int cols = sourceArray.GetLength(1);
          int[,] result = new int[rows - 1, cols];
          for (int i = 0; i < rows; i++)
          {
              for (int j = 0; j < cols; j++)
              {
                  if (i != rowDeleteIndex)
                  {
                      result[i >= rowDeleteIndex ? i - 1 : i, j] = sourceArray[i, j];
                  }
              }
          }
          return result;
      }
      

      所以你可以

      int[,] shipPosition = new int[3, 2] { { 2, 3 }, { 4, 5 }, { 6, 7 } };
      int[,] result = DeleteRow(1, shipPosition);
      

      https://dotnetfiddle.net/rsrjoZ

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-17
        • 1970-01-01
        • 2017-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        相关资源
        最近更新 更多