remove an element from the middle of an array in csharp

To remove an element from the middle of an array in C#, you can use a combination of the Array.Copy method and a for loop to shift the remaining elements back by one position. Here's an example code snippet:

main.cs
int[] arr = new int[] { 1, 2, 3, 4, 5 };
int indexToRemove = 2;

for (int i = indexToRemove; i < arr.Length - 1; i++)
{
    arr[i] = arr[i + 1];
}

Array.Resize(ref arr, arr.Length - 1);
187 chars
10 lines

In this example, we first declare an integer array arr with 5 elements. We then set the indexToRemove variable to the desired index of the element to remove from the array (in this case, index 2, which contains the value 3).

Next, we use a for loop to shift the remaining elements in the array back one position. Starting at the indexToRemove position, we set each element to the value of the element at the next position. This effectively removes the element at the indexToRemove position by shifting all of the elements to its right back by one position.

Finally, we use the Array.Resize method to resize the array to one element smaller, effectively removing the last element (which is now a duplicate of the second-to-last element).

related categories

gistlibby LogSnag