How to remove a specific element from an array?

How can I remove 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 remove an item from index 2?

+3
source share
1 answer

Use the built-in class System.Collections.Generic.List<T>. If you want to remove items, do not make your life harder than it should be.

list.RemoveAt(2);

Keep in mind that the actual code for this is not so complicated. The point is, why not use 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++;
}
+10
source

Source: https://habr.com/ru/post/1787358/


All Articles