3

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?

0

1 Answer 1

10

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.