Holyoxx
Holyoxx

Reputation: 377

How to delete specific element from an array?

How can i delete a specified element from an array?

for example i added elements from an array like this:

        int[] array = new int[5];
        for (int i = 0; i < array.Length; i++) 
        {
            array[i] = i;
        }

How to delete the element from index 2?

Upvotes: 3

Views: 3283

Answers (1)

ChaosPandion
ChaosPandion

Reputation: 78262

Use the built in System.Collections.Generic.List<T> class. If you want to delete elements don't make your life harder than it has to be.

list.RemoveAt(2);

Keep in mind the actual code to do this is not that complex. The thing is, why not take advantage of the built-in classes?

public void RemoveAt(int index)
{
    if (index >= this._size)
    {
        ThrowHelper.ThrowArgumentOutOfRangeException();
    }
    this._size--;
    if (index < this._size)
    {
        Array.Copy(this._items, index + 1, this._items, index, this._size - index);
    }
    this._items[this._size] = default(T);
    this._version++;
}

Upvotes: 10

Related Questions