SelectMany in Linq and Dimension Array?

Why is this code compiled:

byte[][] my2DArray =new byte [][]{ new byte[] {1, 2}, new byte[] {3, 4}, }; var r = my2DArray.SelectMany(f=> f); 

until it is:

 byte[,] my2DArray =new byte [2,2]{ {1, 2}, {3, 4}, }; var r = my2DArray.SelectMany(f=> f); 

doesn't [][] equal [,] ?

Edit

why do I need it?

I need to create one dimensional array so that it is sent to GetArraySum

Of course, I can create an overload, but I wanted to convert mutli dim to one dim. ( GetArraySum also serves as 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(); } 
+2
source share
2 answers

not equal [,]

No. A byte[][] is a jagged array - an array of arrays. Each element of the "external" array is a reference to a normal byte[] (or a null reference, of course).

A byte[,] is a rectangular array - the only object.

Rectangular arrays do not implement IEnumerable<T> , just not a generic IEnumerable , but you can use Cast to cast each element in a byte :

 byte[,] rectangular = ...; var doubled = rectangular.Cast<byte>().Select(x => (byte) x * 2); 

This will simply treat the rectangular array as one sequence of bytes, although it is not a sequence of "subarrays" just as if you were with an uneven array, though ... you could not use Cast<byte[]> for example.

Personally, I rarely use multidimensional arrays of any type - what are you trying to achieve here? There may be a better approach.

EDIT: if you are just trying to sum everything in a rectangular array, it is easy:

 int sum = array.Cast<byte>().Sum(x => (int) x); 

In the end, you don’t care how everything turned out - you just want to get the sum of all the values ​​(provided that I correctly interpreted your question).

+6
source

This does not compile because [,] is a multidimensional array, and [][] is an array of arrays ( msdn )

So your first example will return arrays, where the second is complex

0
source

All Articles