C#: Splitting an array into n parts -


i have list of bytes , want split list smaller parts.

var array = new list<byte> {10, 20, 30, 40, 50, 60}; 

this list has 6 cells. example, want split 3 parts containing each 2 bytes.

i have tried write loops , used 2d arrays achieve purpose don't know correct approach.

            byte[,] array2d = new byte[window, lst.count / window];             var current = 0;             (int = 0; < rows; i++)             {                 (int j = 0; j < cols; j++)                 {                     array2d[i, j] = lst[current++];                 }             } 

a nice way create generic/extension method split array. mine:

/// <summary> /// splits array several smaller arrays. /// </summary> /// <typeparam name="t">the type of array.</typeparam> /// <param name="array">the array split.</param> /// <param name="size">the size of smaller arrays.</param> /// <returns>an array containing smaller arrays.</returns> public static ienumerable<ienumerable<t>> split<t>(this t[] array, int size) {     (var = 0; < (float)array.length / size; i++)     {         yield return array.skip(i * size).take(size);     } } 

moreover, solution deferred. then, call split(size) on array.

var array = new byte[] {10, 20, 30, 40, 50}; var splitarray = array.split(2); 

as requested, here generic/extension method square 2d arrays array:

public static t[,] tosquare2d<t>(this t[] array, int size) {     var buffer = new t[(int)math.ceiling((double)array.length/size), size];     (var = 0; < (float)array.length / size; i++)     {         (var j = 0; j < size; j++)         {             buffer[i, j] = array[i + j];         }     }     return buffer; } 

have fun :)


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -