Thomas Mann
Thomas Mann

Reputation: 95

How to split array in two arrays?

I have one array and want split it in to two:

Now:     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

New_1: [0, 2, 4, 6, 8]

New_2: [1, 3, 5, 7, 9]

So take the one element and skip the next element. Look easy but how can i do it with C#?

Thanks a lot

Upvotes: 0

Views: 1841

Answers (3)

Adil
Adil

Reputation: 148110

You can use linq, Enumerable.Where and get the array with elements that have even and odd indexes.

var New_1 = arr.Where((c,i) => i % 2 == 0).ToArray();
var New_2 = arr.Where((c,i) => i % 2 != 0).ToArray();

You can get the index of element of collection and apply condition to check if index is even or odd and get the arrays according.

Enumerable.Where Method (IEnumerable, Func) filters a sequence of values based on a predicate. Each element's index is used in the logic of the predicate function. The first argument of predicate represents the element to test. The second argument represents the zero-based index of the element within source, msdn

Upvotes: 3

Adriaan Stander
Adriaan Stander

Reputation: 166336

How about something like

int[] arr = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] arr1 = arr.Where((x, i) => i % 2 == 0).ToArray();
int[] arr2 = arr.Where((x, i) => i % 2 == 1).ToArray();

Upvotes: 1

L.B
L.B

Reputation: 116098

int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
List<int[]> twoArr = arr.GroupBy(x => i++ % 2).Select(g => g.ToArray()).ToList();

Upvotes: 0

Related Questions