Two dimensional array slice in C#

后端 未结 3 1586
梦如初夏
梦如初夏 2020-12-03 21:18

I\'m looking to slice a two dimensional array in C#.

I have double[2,2] prices and want to retrieve the second row of this array. I\'ve tried prices[1,], but I have

3条回答
  •  萌比男神i
    2020-12-03 21:34

    The question is if you have a jagged or a multidimensional array... here's how to retrieve a value from either:

     int[,] rectArray = new int[3,3]
      {
          {0,1,2}
          {3,4,5}
          {6,7,8}
      };
    
     int i = rectArray[2,2]; // i will be 8
    
     int[][] jaggedArray = new int[3][3]
      {
          {0,1,2}
          {3,4,5}
          {6,7,8}
      };
    
      int i = jaggedArray[2][2]; //i will be 8
    

    EDIT: Added to address the slice part...

    To get an int array from one of these arrays you would have to loop and retrieve the values you're after. For example:

      public IEnumerable GetIntsFromArray(int[][] theArray) {
      for(int i = 0; i<3; i++) {
         yield return theArray[2][i]; // would return 6, 7 ,8  
      }
      }
    

提交回复
热议问题