Convert 2 dimensional array

拜拜、爱过 提交于 2019-11-26 08:27:27

问题


What is selectMany.ToArray() method? Is it a built in method in C#?

I need to convert two dimensional array to one dimensional array.


回答1:


If you mean a jagged array (T[][]), SelectMany is your friend. If, however, you mean a rectangular array (T[,]), then you can just enumerate the date data via foreach - or:

int[,] from = new int[,] {{1,2},{3,4},{5,6}};
int[] to = from.Cast<int>().ToArray();



回答2:


SelectMany is a projection operator, an extension method provided by the namespace System.Linq.

It performs a one to many element projection over a sequence, allowing you to "flatten" the resulting sequences into one.

You can use it in this way:

int[][] twoDimensional = new int[][] { 
                                      new int[] {1, 2},
                                      new int[] {3, 4},
                                      new int[] {5, 6}
                                     };

int [] flattened = twoDimensional.SelectMany(x=>x).ToArray();



回答3:


my solution:

public struct Array3D<T>
{
    public T[] flatten;
    int x_len;
    int y_len;
    int z_len;

    public Array3D(int z_len, int y_len, int x_len)
    {
        this.x_len = x_len;
        this.y_len = y_len;
        this.z_len = z_len;
        flatten = new T[z_len * y_len * x_len];
    }

    public int getOffset(int z, int y, int x) => y_len * x_len * z + x_len * y + x;

    public T this[int z, int y, int x] {
        get => flatten[y_len * x_len * z + x_len * y + x];
        set => flatten[y_len * x_len * z + x_len * y + x] = value;
    }

    public T this[int flat_index] {
        get => flatten[flat_index];
        set => flatten[flat_index] = value;
    }
}


来源:https://stackoverflow.com/questions/641499/convert-2-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!