0

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

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Don't forget .ToArray()
But he wants an array as the result. Where() returns an IEnumerable
Thanks @elmugrat, so nice of you.
1

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

Comments

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

3 Comments

This would work, but it doesn't give OP the result he wants (two arrays) and is (IMO) less readable than the Where() version
@elmugrat If he wanted to split to 10, would you create 10 arrays manually. No I won't post a bad answer.
If he hadn't said "split it in to two", I'd agree with you, but since he only wants two, I think the improved readability is worth the extra line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.