Optimized code using a foreach loop