Use while-loop to replace foreach for better performance.