27

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.

1

4 Answers 4

20

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();
Sign up to request clarification or add additional context in comments.

3 Comments

What does this do in this T[,] array?
@Hamish Grubijan: It turns the static method into an extension method.
Don't you misplace the row index here as I thought that it should be array[row,column] ?
7
Enumerable.Range(0, 2)
                .Select(x => prices[1,x])
                .ToArray();

Comments

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  
  }
  }

1 Comment

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}
1

In .NET Core 2.1 and later, you can use MemoryMarshal.CreateSpan<T>(T, Int32) method to create a linear span from a multidimensional array and then Slice() the span to your liking.

double[,] table =
{
    { 12.345, 67.890 },
    { 23.456, 78.901 }
};

var tableSpan = MemoryMarshal.CreateSpan(ref table[0, 0], table.Length);
// tableSpan here is linear: [12.345, 67.890, 23.456, 78.901]

Span<double> slice = tableSpan.Slice(2, 2);
double[] oneDimension = slice.ToArray();
// at this point both slice and oneDimension are: [23.456, 78.901]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.