How to delete a chosen element in array?

I’m assuming you are working with a basic array of strings:

var strItems = new string[] { "1", "2", "3", "4", "5" };

In .NET, that array is always going to be 5 elements long. In order to remove an element, you are going to have to copy the remaining elements to a new array and return it. Setting the value at a position to null does not remove it from the array.

Now, with things like LINQ this is very easy (not shown here), or you could cheat using the List<> collection and do this:

var list = new List<string>(strItems);
list.Remove("3");
strItems = list.ToArray();

But I don’t think that’s going to teach you anything.

The first step is to find the index of the element you wish to remove. You can use Array.IndexOf to help you out. Let’s find the middle element, “3”:

int removeIndex = Array.IndexOf(strItems, "3");

If the element was not found, it will return a -1, so check for that before doing anything.

if (removeIndex >= 0)
{
     // continue...
}

Finally you have to copy the elements (except the one at the index we don’t want) to a new array. So, altogether, you end up with something like this (commented for explanation):

string strInput = Console.ReadLine();
string[] strItems = new string[] { "1", "2", "3", "4", "5" };

int removeIndex = Array.IndexOf(strItems, strInput);

if (removeIndex >= 0)
{
    // declare and define a new array one element shorter than the old array
    string[] newStrItems = new string[strItems.Length - 1];

    // loop from 0 to the length of the new array, with i being the position
    // in the new array, and j being the position in the old array
    for (int i = 0, j = 0; i < newStrItems.Length; i++, j++)
    {
        // if the index equals the one we want to remove, bump
        // j up by one to "skip" the value in the original array
        if (i == removeIndex)
        {
            j++;
        }

        // assign the good element from the original array to the
        // new array at the appropriate position
        newStrItems[i] = strItems[j];
    }

    // overwrite the old array with the new one
    strItems = newStrItems;
}

And now strItems will be the new array, minus the value specified for removal.

Leave a Comment