[Solved] c# replace odd elements of array with even elements of another array


Even though this is a very specific problem, here’s a solution:

var array1 = new[] { 2, 5, 7, 8, 9, 4 };
var array2 = new [] { 4, 8, 2, 1, 5, 8 };

array1 = array1.Select((i, index) => i % 2 == 1 ? array2[index] : i).ToArray();
//result: int[6] { 2, 8, 2, 8, 5, 4 }

It takes the elements from the first array, checks wether it’s even and replaces it if it’s odd with the item at that position of the other array.

I’m not totally sure wether this is what you’re looking for, otherwise kindly clarify your problem.

For example you could mean items with an odd index:

var array1 = new[] { 2, 5, 7, 8, 9, 4 };
var array2 = new[] { 4, 8, 2, 1, 5, 8 };

array1 = array1.Select((i, index) => index % 2 == 1 ? array2[index-1] : i).ToArray();
//result: int[6] { 2, 4, 7, 2, 9, 5 }

1

solved c# replace odd elements of array with even elements of another array