4

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}

Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
Tian Xiao
  • 239
  • 2
  • 7

1 Answers1

10

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();
Zein Makki
  • 29,485
  • 6
  • 52
  • 63