score:71

Accepted answer

You can use linq:

firstArray = array.Take(array.Length / 2).ToArray();
secondArray = array.Skip(array.Length / 2).ToArray();

Why this works, despite the parity of the original array size?

The firstArray takes array.Length / 2 elements, and the second one skips the first array.Length / 2 elements, it means there isn't any conflict between these two arrays. Of course if the number of elements is odd we cannot split the array into two equal size parts.

If you want to have more elements in the first half (in the odd case), do this:

firstArray = array.Take((array.Length + 1) / 2).ToArray();
secondArray = array.Skip((array.Length + 1) / 2).ToArray();

score:-2

Just in case someone wants to use a function instead:

    static void Main(string[] args)
    {
        string[] ar = { "apple", "orange", "banana", "pear", "lemon" };

        int half =  ar.Length / 2;

        //  Console.WriteLine(string.Join(',', Split(ar,0, half)));

        Console.WriteLine(string.Join(',', Split(ar,half, ar.Length)));

        Console.ReadKey();
    }


    public static IEnumerable<T> Split<T>(IEnumerable<T> items, int start, int end)
    {
        return items.Skip(start).Take(end);
    }

score:2

You can achive that quite easily using range notation:

var x = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
var pivot = x.Length / 2;
var p1 = x[..pivot];
var p2 = x[pivot..];

score:3

string[] words = { "apple", "orange", "banana", "pear", "lemon" };
var halfWay = words.Length/2;

var firstHalf = words.Take(halfWay);
var secondHalf = words.Skip(halfWay);

score:4

A more generalized approach that will split it into as many parts as you specify:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
        {
          return list.Select((item, index) => new {index, item})
                       .GroupBy(x => (x.index + 1) / (list.Count()/parts) + 1)
                       .Select(x => x.Select(y => y.item));
        }

*Edited Thanks skarmats

score:7

If you don't want to/can't use LINQ you can simply do:

    string[] words = { "apple", "orange", "banana", "pear", "lemon" };
    string[] firstarray, secondarray;
    int mid = words.Length / 2;
    firstarray = new string[mid];
    secondarray = new string[words.Length - mid];
    Array.Copy(words, 0, firstarray, 0, mid);
    Array.Copy(words, mid, secondarray, 0, secondarray.Length);

score:8

string[] words = {"apple", "orange", "banana", "pear", "lemon"};
int mid = words.Length/2;
string[] first = words.Take(mid).ToArray();
string[] second = words.Skip(mid).ToArray();

Related Query

More Query from same tag