I get the feeling that this piece of code (inside the foreach) has multiple responsibilities; can you separate it into methods with descriptive names?