encapsulating the 2 foreach statements into a private method to eliminate duplication