How to get a dimension (slice) from a multidimensional array

前端 未结 4 904
时光取名叫无心
时光取名叫无心 2020-12-01 12:16

I\'m trying to figure out how to get a single dimension from a multidimensional array (for the sake of argument, let\'s say it\'s 2D), I have a multidimensional array:

4条回答
  •  -上瘾入骨i
    2020-12-01 12:41

    No. You could of course write a wrapper class that represents a slice, and has an indexer internally - but nothing inbuilt. The other approach would be to write a method that makes a copy of a slice and hands back a vector - it depends whether you want a copy or not.

    using System;
    static class ArraySliceExt
    {
        public static ArraySlice2D Slice(this T[,] arr, int firstDimension)
        {
            return new ArraySlice2D(arr, firstDimension);
        }
    }
    class ArraySlice2D
    {
        private readonly T[,] arr;
        private readonly int firstDimension;
        private readonly int length;
        public int Length { get { 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]
        {
            get { 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);
            for (int i = 0; i < slice.Length; i++)
            {
                Console.WriteLine(slice[i]);
            }
        }
    }
    

提交回复
热议问题