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

末鹿安然 提交于 2019-12-24 01:18:02

问题


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}


回答1:


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();


来源:https://stackoverflow.com/questions/37382990/how-to-split-an-array-to-2-arrays-with-odd-and-even-indices-respectively

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!