How to remove an item at an array position?

Asked

Viewed 5,565 times

4

Example:

string[] x = {"3","2","1"};

I just want to take off the item "2" array x, resulting in:

x = {"3","1"};

1 answer

3


Turn the vector into a List<T> and use the method RemoveAt(int).

string[] x = {"3","2","1"};
var lista = x.ToList(); // cria um objeto do tipo List<string> a partir do vetor
lista.RemoveAt(1); // remove o item na posição 1
x = lista.ToArray(); // recria o vetor a partir da lista

If you do not know the position of the element to be excluded, do so:

string[] x = {"3","2","1"};
int[] lista = x.ToList(); // cria o objeto do tipo List<string> a partir do vetor
lista.Remove("2"); // remove a primeira ocorrência do elemento que for equivalente a "2"
x = lista.ToArray()l // recria o vetor a partir da lista

Sometimes you can scan your code and see if there is even a need to use an array. Often use an implementation of IEnumerable, like the List<T>, makes it much easier.

They are very specific when there is a need to use an array. If you need to add and remove items it is convenient to use an List<T>, for example. Resizing arrays is costly.

I’ll leave "Arrays considered somewhat Harmful" by Eric Lippert as a recommendation for reading.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.