Remove all elements from the list without the Clean() method, is there a way?

Asked

Viewed 43 times

0

For example I wanted to remove the elements from the list in this way:

public class List : MonoBehaviour {

List<string> inventário = new List<string>();

void Start () {



    for(int i = 0;i<=10;i++){
        inventário.Add("slot" + i);
    }

    Debug.Log(inventário[1]);

    for(int i=0;i<inventário.Count;i++){
        inventário.Remove(inventário[i]);
    }

But for some reason it leaves only 5 elements in the array list.

  • 1

    And why would you do that?

  • To learn more and more about the list command and not to lose the practice of loop for.

  • You didn’t convince me of the need. I think you’ve learned to do something wrong.

1 answer

1


Change this:

for(int i=0;i<inventário.Count;i++){
    inventário.Remove(inventário[i]);
}

That’s why:

while (inventário.Count != 0) {
    inventário.Remove(inventário[0]);
}

The reason is that in your first for, it removes the element at position 0, but then the element that was at position 1 goes to 0. Then you go to position 1 and remove the element that was there, and with that what was in 2 goes to 1, and so on. As a result, with each iteration you eliminated one element and also saved another element, eliminating only half of them (those that had even indexes).

Already in that while, he insists on removing the first element until there is no more first element.

  • Thank you very much!

Browser other questions tagged

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