为什么这个code编译:
字节[] [] my2DArray =新的字节[] [] {
新的byte [] {1,2},
新的byte [] {3,4},
};
变种R = my2DArray.SelectMany(F =&F)的温度;
而这个人是不是:
字节[,] my2DArray =新的字节[2,2] {
{1,2},
{3,4},
};
变种R = my2DArray.SelectMany(F =&F)的温度;
不是 [] []
是为 [,]
?
为什么我需要吗?
我需要创建一个一维数组,因此将被发送到 GetArraySum
我可以创造过载,但我想改造辑阵暗淡成一个暗淡。 ( GetArraySum
供应也纯维数组)。
无效的主要()
{
字节[] [] my2DArray =新的字节[] [] {
新的byte [] {1,2},
新的byte [] {3,4},
};
变种总和= GetArraySum(my2DArray.SelectMany中(f =&F)的温度.ToArray());
}
INT GetArraySum(byte []的AR)
{
返回ar.Select相关(r =>(int)的r)的.SUM();
}
解决方案
不是[] []是为[,]
没有。 A 字节[] []
是的 交错数组的 - 数组的数组。 外数组的每个元素是一个引用到正常字节[]
(或空引用,当然)。
A 字节[,]
是的 矩形阵列的 - 一个对象
矩形阵列不落实的IEnumerable< T>
,只有非泛型的IEnumerable
,但你可以使用铸造
每个项目转换为字节
:
字节[,]长方形= ...;
VAR一倍= rectangular.Cast<字节>()选择。(X =>(字节)X * 2);
这将只把矩形阵列字节的单个序列,虽然 - 它的不是的子阵列的以同样的方式顺序,你会与交错数组虽然...你不能使用演员LT; byte []的>
例如:
我个人很少使用任何类型的多维数组 - 什么是你想在这里实现?有可能是一个更好的办法。
编辑:如果你只是想来概括一切都在一个矩形阵列,它很容易:
INT总和= array.Cast<字节>()和(X =>(INT)X);
毕竟,你真的不关心事情是如何布局 - 你只是希望所有的值的总和(假设我已经跨$ P $正确PTED你的问题)
。Why this code compiles :
byte[][] my2DArray =new byte [][]{
new byte[] {1, 2},
new byte[] {3, 4},
};
var r = my2DArray.SelectMany(f=> f);
while this one isn't :
byte[,] my2DArray =new byte [2,2]{
{1, 2},
{3, 4},
};
var r = my2DArray.SelectMany(f=> f);
isn't [][]
is as [,]
?
why do I need that ?
I need to create a single dimension array so it will be sent to GetArraySum
of course I can create overload , but I wanted to transform the mutli dim into one dim. (GetArraySum
serves also pure dimensional arrays).
void Main()
{
byte[][] my2DArray =new byte [][]{
new byte[] {1, 2},
new byte[] {3, 4},
};
var sum = GetArraySum(my2DArray.SelectMany(f=> f).ToArray());
}
int GetArraySum(byte [] ar)
{
return ar.Select(r=>(int)r).Sum();
}
解决方案
isn't [][] is as [,]
No. A byte[][]
is a jagged array - an array of arrays. Each element of the "outer" array is a reference to a normal byte[]
(or a null reference, of course).
A byte[,]
is a rectangular array - a single object.
Rectangular arrays don't implement IEnumerable<T>
, only the non-generic IEnumerable
, but you could use Cast
to cast each item to a byte
:
byte[,] rectangular = ...;
var doubled = rectangular.Cast<byte>().Select(x => (byte) x * 2);
That will just treat the rectangular array as a single sequence of bytes though - it isn't a sequence of "subarrays" in the same way as you would with a jagged array though... you couldn't use Cast<byte[]>
for example.
Personally I rarely use multidimensional arrays of either kind - what are you trying to achieve here? There may be a better approach.
EDIT: If you're just trying to sum everything in a rectangular array, it's easy:
int sum = array.Cast<byte>().Sum(x => (int) x);
After all, you don't really care about how things are laid out - you just want the sum of all the values (assuming I've interpreted your question correctly).