What is selectMany.ToArray()
method? Is it a built in method in C#
?
I need to convert two dimensional array to one dimensional array.
Marc Gravell
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();
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();
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