Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

c# - 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();
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...