-1

I am trying to remove one item from the list until the list is empty. My code only successfully removes one item from the list and then cause an error. How do I fix this?

public void ReleaseAllAnimals()
{
    int i = 0;
    foreach (var value in _farmAnimals)
    {
        _farmAnimals.RemoveAt(i);
        Console.WriteLine(value.Species());
        i++;
    }
}

enter image description here

stasiaks
  • 1,268
  • 2
  • 14
  • 31
Krishneil
  • 1,432
  • 1
  • 18
  • 26

2 Answers2

0

You should not be modifying the collection while enumerating it. As you want to remove elements you should use for loop instead with indexer so that you do not face the issue.

You can loop through the list in reverse order like and remove from the end item one by one:

for(int i=_farmAnimals.Count -1; i >= 0; i--)
{
      var species = _farmAnimals[i].Species(); // get species of current item
      _farmAnimals.RemoveAt(i); // remove from list
      Console.WriteLine(species); // display it
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • 1
    This will only remove 2 items from the list of 4. I have already tried this code. Once the counter(i) becomes 2 then it will exit the for loop. – Krishneil Aug 18 '18 at 11:16
  • @Krishneil it will remove all items one by one – Ehsan Sajjad Aug 18 '18 at 11:17
  • I just run your code it only displays 2 item from 4 on the list(I already wrote this myself but for peace of mind I did it anyway). The for statement will only be valid for the first two iterations the third iteration it will fail as I will become 3 and list count will be 2. This will not work I am 100% correct. seems innocent but it fails. – Krishneil Aug 18 '18 at 11:22
  • @Krishneil you will need to loop it in reverse order, i updated the post. – Ehsan Sajjad Aug 18 '18 at 11:33
0

You can remove each item from the first of your List by using RemoveAt(0)

Change your code to this:

int size = _farmAnimals.Count;
for(int i = 0; i < size; i++)
{
    var s = _farmAnimals[0].Species();
    Console.WriteLine(s);
    _farmAnimals.RemoveAt(0);
}

I hope it helps you

Ehsan Mohammadi
  • 1,168
  • 1
  • 15
  • 21