Moose Pickard

Moose Pickard

  • NA
  • 64
  • 70.3k

Problem with modifying List

Oct 14 2010 4:11 AM
Hi

I'm struggling with this loop. It gives me "Collection was modified; enumeration operation may not execute."
I think it is about changing the CarsList. The RentIn method adds the car object to CarsList. So it modifies the list in the foreach loop. If I am correct, how could I use these methods? Since they modify the list on the run. I don't see any other way to do it, without foreach.

foreach (CarRental carRental in CarRentalProgram.CarRentalsList){
   foreach (Car car in carRental.CarsList){
      if(car.Name == "Mercedes"){
      car.Status = CarStatus.Out;
      carRental.RentIn(car, 33, carRental.ID);
      break;
      }
   }
}


Thank you


Answers (1)