C#将多维数组转换为单个数组并返回! [英] C# Convert multidimensional array to single array and back !
本文介绍了C#将多维数组转换为单个数组并返回!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hello Codeproject,
我如何转换
[XmlIgnore]
public Block [,] _Blocks { get ; set ; }
To:
public 阻止[] _Blocks { get ; set ; }
回到:
public 阻止[] _Blocks { get ; set ;我需要保存块列表,但是XML序列化器不允许多维数组。解决方案
如果您没有任何规范,这里有一些int []转换的示例代码。注意:这仅适用于具有相同宽度和高度的多维数组...
static int [,] SingleToMulti( int [] array)
{
int index = 0 ;
int sqrt =( int )Math.Sqrt(array.Length);
int [,] multi = new int [sqrt,sqrt];
for ( int y = 0 ; y < sqrt; y ++)
{
for (< span class =code-keyword> int x = 0 ; x < sqrt ; x ++)
{
multi [x,y] = array [index];
index ++;
}
}
返回多个;
}
静态 int [] MultiToSingle( int [,] array)
{
< span class =code-keyword> int index = 0 ;
int width = array.GetLength( 0 );
int height = array.GetLength( 1 );
int [] single = new int [width * height];
for ( int y = 0 ; y < height; y ++)
{
for (< span class =code-keyword> int x = 0 ; x < 宽度; x ++)
{
single [index] = array [x,y];
index ++;
}
}
返回单;
}
Hello Codeproject,
How would I converted
[XmlIgnore]
public Block[,] _Blocks { get; set; }
To:
public Block[] _Blocks { get; set; }
And back to:
public Block[] _Blocks { get; set; }
,
I need this for my XML Serializer, because I need to save the list of blocks, but the XML serializer does not allow Multi-dimensional array.
解决方案 Here''s some sample code of an int[] conversion if you don''t have any specifications. NOTE: this only works with multi-dimensional array''s with the same width and height...
static int[,] SingleToMulti(int[] array)
{
int index = 0;
int sqrt = (int)Math.Sqrt(array.Length);
int[,] multi = new int[sqrt, sqrt];
for (int y = 0; y < sqrt; y++)
{
for (int x = 0; x < sqrt; x++)
{
multi[x, y] = array[index];
index++;
}
}
return multi;
}
static int[] MultiToSingle(int[,] array)
{
int index = 0;
int width = array.GetLength(0);
int height = array.GetLength(1);
int[] single = new int[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
single[index] = array[x, y];
index++;
}
}
return single;
}
这篇关于C#将多维数组转换为单个数组并返回!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文