OneBite.Dev - Coding blog in a bite size

Remove Item From Array In C#

Code snippet for how to Remove Item From Array In C# with sample and detail explanation

Removing an item from an array in C# isn’t as straightforward as it may seem because arrays are fixed in size and cannot be resized dynamically. However, we can accomplish this by creating a new array or using a different data structure like List.

Code snippet for Removing Item from Array

The following code shows an example of how to remove an item from an array in C# by creating a new list, copying the items to it, and then converting it back to the array.

int[] originalArray = {1, 2, 3, 4, 5};

List<int> list = new List<int>(originalArray);
list.RemoveAt(3);  // Removal index. 

originalArray = list.ToArray();

In this code snippet, we’ve declared an array named originalArray and initialized it with five integer values — 1, 2, 3, 4 and 5. We’ve then created a List of integers list and initialized it with the values from originalArray. We’ve then removed an item from list using the RemoveAt() method. Finally, we’ve converted list back to an array and assigned it back to originalArray.

Code Explanation for Code snippet for Removing Item from Array

In C#, arrays are fixed in size. This means you are not able to directly remove an item from an array. However, we are able to work around this by creating a new array or using a different data structure. In this case, the snippet makes use of the List data structure for this purpose.

First, it initializes an array named originalArray with five integer values: 1, 2, 3, 4 and 5. A List of integers named list is then declared and the array values are passed into the list via the List constructor.

In the next line, it uses the RemoveAt() method, which removes an element at the specified index from the List. Here, it removes the fourth item (with index 3, because index in C# starts at 0), or the number ‘4’ from list.

Once the desired item is removed, the list is then converted back to an array using the ToArray() method. This new array, which no longer includes the removed element, is then assigned back to the originalArray variable. Hence, through this code, we successfully removed an item from an array in C#.

This is a simple and efficient solution to the problem, albeit it’s not directly removing an item from the array, but by using the List data structure as an intermediary and then converting it back to an array. It’s important to note that the indices of the array elements change after the removal operation.

c-sharp