Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array to 2 arrays with odd and even indices respectively? [duplicate]

Tags:

c#

collections

How to split an array to 2 arrays with odd and even indices respectively? For example

int[] a = new int[]{1, 3, 7, 8};

then get two arrays

a1: {1, 7}
a2: {3, 8}

like image 352
Tian Xiao Avatar asked Oct 16 '25 10:10

Tian Xiao


1 Answers

Simple using the overload of Where than contains the index which:

Filters a sequence of values based on a predicate. Each element's index is used in the logic of the predicate function.

int[] a = new int[] { 1, 3, 7, 8 };

int[] aEven = a.Where((x, i) => i % 2 == 0).ToArray();
int[] aOdd = a.Where((x, i) => i % 2 != 0).ToArray();
like image 177
Zein Makki Avatar answered Oct 19 '25 10:10

Zein Makki