SelectMany in Linq and dimensional array?

后端 未结 2 1724
名媛妹妹
名媛妹妹 2020-12-19 21:55

Why this code compiles :

byte[][] my2DArray =new  byte  [][]{  
                        new byte[] {1, 2},
                        new byte[] {3, 4},
                 


        
相关标签:
2条回答
  • 2020-12-19 22:13

    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

    0 讨论(0)
  • 2020-12-19 22:14

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

    0 讨论(0)
提交回复
热议问题