Domanda

Sto cercando di capire come ottenere una sola dimensione di un array multidimensionale (per amor di discussione, diciamo che di 2D), ho un array multidimensionale:

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

Se fosse una matrice irregolare, vorrei semplicemente chiamare d[0] e che mi avrebbe dato una serie di {1, 2, 3, 4, 5}, c'è un modo per ottenere lo stesso con una matrice 2D?

È stato utile?

Soluzione

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

Altri suggerimenti

Improved version of that answer:

public static IEnumerable<T> SliceRow<T>(this T[,] array, int row)
{
    for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++)
    {
        yield return array[row, i];
    }
}

public static IEnumerable<T> SliceColumn<T>(this T[,] array, int column)
{
    for (var i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++)
    {
        yield return array[i, column];
    }
}

Rectangular arrays are not built for this purpose. If you need that type of functionality, you should switch to a jagged array. It is pretty simple to write a function that will convert a rectangular array into a jagged one.

You could also simply rebuild that array by calling GetLength(int dimension) on the appropriate dimension, and then indexing it properly to retrieve each value. It would be cheaper than converting the entire array, but the cheapest option is to change it to use jagged arrays.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top