0

How to convert an array into list of arrays of some size in C#?

For example:

 byte[] incoming = {1,2,3,4};
 List<byte[]> chunks = new List<byte[]>; 

What I'm trying to get is something like this, get a chunk of some size, here below I used 2.

 chunks[0] = {1,2};
 chunks[1] = {3,4};

Thanks in Advance!

joce
  • 9,624
  • 19
  • 56
  • 74
Vikyboss
  • 940
  • 2
  • 11
  • 23

1 Answers1

7

This helper method should make things easier:

public static byte[] Partial(byte[] source, int start, int length)
{
    byte[] b = new byte[length];
    Array.Copy(source, start, b, 0, length);
    return b;
}    

From there, you can do something like:

for (int index = 0; index < incoming.Length; index += 2)
{
    List.Add(Partial(incoming, index, 2));
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 2
    You could just use something like the latter part to add to a list returning `new byte[] {incoming[index],incoming[index+1]}` . Also, if you need an array, then you just use `listvar.ToArray()` to get the array at the end. – David Burton Jun 01 '12 at 16:13
  • Thanks! Since Performance is important, I will go with this. – Vikyboss Jun 01 '12 at 16:15
  • Thanks David! Thanks for the tips. – Vikyboss Jun 01 '12 at 16:21