Refactoring some foreach loops