## 5 replies

Last post Jun 11, 2018 01:10 PM by hugo

• stevana

Member

34 Points

120 Posts

### How to split array of integers?

Hi there,

I have an array of integers, like:

a[0]=1; a[1]=5; a[2]=89; a[3]=125; a[4]=203

and variable divNo containing the number I have to find in that array.

If we assume that divNo is 89, array has to be split in two: first one from a[0] to a[2]=divNo=89 and second one from a[3] to a[4].

How do I do that?

Kind regards

• Nasser Malik

Star

13450 Points

2764 Posts

### Re: How to split array of integers?

May 26, 2018 08:22 PM|Nasser Malik|LINK

Following will done the trick for you

```class Program
{
static void Main(string[] args)
{
int[] a = new[] { 1, 5, 89, 125, 203 };
var divNo = 89;

var index = Array.IndexOf(a, divNo);

if (index > -1)
{
Split(a, index + 1, out int[] b, out int[] c);

Console.WriteLine("Elements in First Array");

foreach (var i in b)
{
Console.WriteLine(i);
}

Console.WriteLine("Elements in Second Array");

foreach (var i in c)
{
Console.WriteLine(i);
}

}
}

public static void Split<T>(T[] array, int index, out T[] first, out T[] second)
{
first = array.Take(index).ToArray();
second = array.Skip(index).ToArray();
}
}```
Skype: maleknasser1
• stevana

Member

34 Points

120 Posts

### Re: How to split array of integers?

Thanks a lot Nasser Malik, it works great!

Regards

• hugo

Member

30 Points

106 Posts

### Re: How to split array of integers?

Use LINQ

`int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };`

`var first = numbers.Take(Array.IndexOf(numbers, 6) + 1);`
`var rest = numbers.Skip(Array.IndexOf(numbers, 6) + 1);`

• PaulTheSmith

Participant

960 Points

503 Posts

### Re: How to split array of integers?

var first = numbers.TakeWhile(n => n <=89);

var second = numbers.SkipWhile(n => n<= 89);

• hugo

Member

30 Points

106 Posts