如何从多维数组中获取维度(切片) [英] How to get a dimension (slice) from a multidimensional array

查看:30
本文介绍了如何从多维数组中获取维度(切片)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何从多维数组中获取单维(为了论证,假设它是二维的),我有一个多维数组:

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:

double[,] d = new double[,] { { 1, 2, 3, 4, 5 }, { 5, 4, 3, 2, 1 } };

如果它是一个锯齿状数组,我会简单地调用 d[0] 并且它会给我一个 {1, 2, 3, 4, 5},有没有办法用二维数组实现同样的效果?

If it was a jagged array, I would simply call d[0] and that would give me an array of {1, 2, 3, 4, 5}, is there a way I can achieve the same with a 2D array?

推荐答案

没有.您当然可以编写一个表示切片的包装类,并在内部具有索引器 - 但没有内置.另一种方法是编写一个方法来制作切片的复制并返回一个向量 - 这取决于您是否想要复制.

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<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 { 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]);
        }
    }
}

这篇关于如何从多维数组中获取维度(切片)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆