25

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 a feeling it might be something else.

Thanks in advance.

MerickOWA
  • 7,453
  • 1
  • 35
  • 56
omarish
  • 575
  • 2
  • 7
  • 15
  • Strange but it still not possible for C# https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges . And works perfectly for F# https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/slices – Andrii Apr 08 '22 at 21:29

3 Answers3

19

There's no direct "slice" operation, but you can define an extension method like this:

public static IEnumerable<T> SliceRow<T>(this T[,] array, int row)
{
    for (var i = 0; i < array.GetLength(0); i++)
    {
        yield return array[i, row];
    }
}

double[,] prices = ...;

double[] secondRow = prices.SliceRow(1).ToArray();
dtb
  • 213,145
  • 36
  • 401
  • 431
6
Enumerable.Range(0, 2)
                .Select(x => prices[1,x])
                .ToArray();
1

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<int> GetIntsFromArray(int[][] theArray) {
  for(int i = 0; i<3; i++) {
     yield return theArray[2][i]; // would return 6, 7 ,8  
  }
  }
Robban
  • 6,729
  • 2
  • 39
  • 47
  • 4
    OP wrote" "...want to retrieve the second row..." In your example, I think OP wants jaggedArray[2] or an int[3] that contains {6,7,8} – JeffH Sep 10 '09 at 15:59