C# Splitting An Array

后端 未结 9 1338
情深已故
情深已故 2020-12-10 00:39

I need to split an array of indeterminate size, at the midpoint, into two separate arrays.

The array is generated from a list of strings using ToArray().

<         


        
9条回答
  •  独厮守ぢ
    2020-12-10 01:21

    I also want to add a solution to split an array into several smaller arrays containing a determined number of cells.

    A nice way would be to create a generic/extension method to split any array. This is mine:

    /// 
    /// Splits an array into several smaller arrays.
    /// 
    /// The type of the array.
    /// The array to split.
    /// The size of the smaller arrays.
    /// An array containing smaller arrays.
    public static IEnumerable> Split(this T[] array, int size)
    {
        for (var i = 0; i < (float)array.Length / size; i++)
        {
            yield return array.Skip(i * size).Take(size);
        }
    }
    

    Moreover, this solution is deferred. Then, simply call split(size) on your array.

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

    Have fun :)

提交回复
热议问题