A condition like this with a big block of code can easily be refactored. This foreach should be very small and calling another method.