C# 转换二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/641499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert 2 dimensional array
提问by Manoj
What is selectMany.ToArray()
method? Is it a built in method in C#
?
什么是selectMany.ToArray()
方法?它是内置方法C#
吗?
I need to convert two dimensional array to one dimensional array.
我需要将二维数组转换为一维数组。
回答by CMS
SelectManyis a projection operator, an extension method provided by the namespace System.Linq.
SelectMany是一个投影运算符,是命名空间 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();
回答by Marc Gravell
If you mean a jaggedarray (T[][]
), SelectMany
is your friend. If, however, you mean a rectangulararray (T[,]
), then you can just enumerate the date data via foreach
- or:
如果您的意思是锯齿状数组 ( T[][]
),那么它SelectMany
就是您的朋友。但是,如果您的意思是矩形数组 ( T[,]
),那么您可以通过foreach
- 或:
int[,] from = new int[,] {{1,2},{3,4},{5,6}};
int[] to = from.Cast<int>().ToArray();
回答by iperov
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;
}
}