c# - How to get a dimension (slice) from a multidimensional array -
i'm trying figure out how single dimension multidimensional array (for sake of argument, let's it's 2d), have multidimensional array:
double[,] d = new double[,] { { 1, 2, 3, 4, 5 }, { 5, 4, 3, 2, 1 } };
if jagged array, call d[0]
, give me array of {1, 2, 3, 4, 5}
, there way can achieve same 2d array?
no. of course write wrapper class represents slice, , has indexer internally - nothing inbuilt. other approach write method makes copy of slice , hands vector - depends whether want copy or not.
using system; static class arraysliceext { public static arrayslice2d<t> slice<t>(this t[,] arr, int firstdimension) { return new arrayslice2d<t>(arr, firstdimension); } } class arrayslice2d<t> { private readonly t[,] arr; private readonly int firstdimension; private readonly int length; public int length { { return length; } } public arrayslice2d(t[,] arr, int firstdimension) { this.arr = arr; this.firstdimension = firstdimension; this.length = arr.getupperbound(1) + 1; } public t this[int index] { { return arr[firstdimension, index]; } set { arr[firstdimension, index] = value; } } } public static class program { static void main() { double[,] d = new double[,] { { 1, 2, 3, 4, 5 }, { 5, 4, 3, 2, 1 } }; var slice = d.slice(0); (int = 0; < slice.length; i++) { console.writeline(slice[i]); } } }
Comments
Post a Comment