将for循环转换为foreach

本文关键字:foreach 转换 循环 for | 更新日期: 2023-09-27 18:22:21

所以我有一段运行良好的代码,但在我的作业中,教授希望代码使用foreach语句。我唯一能让它工作的方法就是用for循环。有人知道如何将for循环转换为foreach语句吗?

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CheckZips.cs
{
class Program
{
    static void Main(string[] args)
    {
        int[] zips = new int[10] { 07950, 07840, 07828, 07836, 07928, 07869, 07849, 07852, 07960, 07876 };
        int correctZipCode;
        int input;
        Console.WriteLine("Enter a zip code.");
        input = int.Parse(Console.ReadLine());
        correctZipCode = Convert.ToInt32(input);
        bool found = false;
        for (int i = 0; i < zips.Length; ++i)
        {
            if(correctZipCode == zips[i])
            {
                found = true;
                break;
            }
        }
        if (found)
        {
            Console.WriteLine("We deliver to that zip code.");
        }
        else
        {
            Console.WriteLine("We do not deliver to that zip code.");
        }
    }
}

}

将for循环转换为foreach

foreach可以这样实现:

foreach (int zip in zips)
{
    if (zip == correctZipCode)
    {
      found = true;
      break;
    }
}