To filter every other element of an array in C#, you can use a simple iteration with the modulo operator %
. Here's an example code block:
main.cs337 chars15 lines
Here, we first create an integer array array
with some sample values. We also create another integer array filteredArray
with half the length of array
(rounded up) to account for the possible odd length.
We then use a for
loop to iterate through every other element of array
(starting from index 0) and add them to filteredArray
. The index of filteredArray
is incremented at each iteration. We use the modulo operator %
to check if the current index is even.
Finally, we use a foreach
loop to print the filtered array to the console.
gistlibby LogSnag