Removing foreach loops to avoid nested iterator exception