0

How can I break an array into 2 arrays in c#

for e.g I have an array [1,2,3,4,5,6,7,8,9,10] break it in to [1,2,3,4,5] and [6,7,8,9,10]

2

4 Answers 4

4

Using Linq

var a = new[] {1,2,3,4,5,6,7,8,9,10}
var a1 = a.Take(a.Length / 2).ToArray();
var a2 = a.Skip(a.Length / 2).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

2

With Linq:

var source = new int[] {1,2,3,4,5,6,7,8,9,10};
var firstHalf = source.Take(source.Length/2).ToArray();
var secondHalf = source.Skip(source.Length/2).ToArray();

With Array.Copy:

var source = new int[] {1,2,3,4,5,6,7,8,9,10};
var firstHalf = new int[source.Length/2];
var secondHalf = new int[source.Length - source.Length/2];
Array.Copy(source, firstHalf, firstHalf.Length];
Array.Copy(source, firstHalf.Length, secondHalf, 0, secondHalf.Length];

Comments

0

You could use the following method to split an array into 2 separate arrays

public void Split<T>(T[] array, int index, out T[] first, out T[] second) {
  first = array.Take(index).ToArray();
  second = array.Skip(index).ToArray();
}

public void SplitMidPoint<T>(T[] array, out T[] first, out T[] second) {
  Split(array, array.Length / 2, out first, out second);
}

Usage:

int[] myArray = new int[] { 1,2,3,4,5,6,7,8,9,10 };
int[] newArray1;
int[] newArray2;

SplitMidPoint<int>(myArray, out newArray1, out newArray2);

From: C# Splitting An Array

Comments

0


    public static T[] SubArray(this T[] data, int index, int length)
    {
          T[] result = new T[length];
          Array.Copy(data, index, result, 0, length);
          return result;
    }
    public void Split(T[] Source, T[] arr1,T[] arr2)
    {
         if(source.Length == 0)
         {
            arr1 = arr2 = new T[0];
            return ;
         } 
         int half = source.Length/2;
         arr1 = source.SubArray(0, half);
         arr2 = source.SubArray(half-1, half);
    } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.