Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dimensional array slice in C#

Tags:

arrays

c#

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.

like image 889
omarish Avatar asked Sep 10 '09 15:09

omarish


People also ask

Can you slice an array in C?

Array-slicing is supported in the print and display commands for C, C++, and Fortran.

What is two dimension array in C?

A two-dimensional array in C can be thought of as a matrix with rows and columns. The general syntax used to declare a two-dimensional array is: A two-dimensional array is an array of several one-dimensional arrays. Following is an array with five rows, each row has three columns: int my_array[5][3];

What is 2D array in C with example?

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure.

What is array slice explain with example?

Common examples of array slicing are extracting a substring from a string of characters, the "ell" in "hello", extracting a row or column from a two-dimensional array, or extracting a vector from a matrix. Depending on the programming language, an array slice can be made out of non-consecutive elements.


1 Answers

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();
like image 178
dtb Avatar answered Oct 14 '22 10:10

dtb