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.
Array-slicing is supported in the print and display commands for C, C++, and Fortran.
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];
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With