Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SelectMany in Linq and dimensional array?

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 [,] ?

edit

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();
 }
like image 629
Royi Namir Avatar asked Feb 21 '26 10:02

Royi Namir


2 Answers

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).

like image 78
Jon Skeet Avatar answered Feb 23 '26 22:02

Jon Skeet


This wont compile, because [,] is multidimensional array and [][] is array-of-arrays (msdn)

So, your first example will return arrays, where as second - it is complicated

like image 32
JleruOHeP Avatar answered Feb 23 '26 23:02

JleruOHeP