将for循环转换为foreach

时间:2015-11-18 15:50:24

标签: c# for-loop foreach

所以我有这段代码可以正常工作,但是对于我的任务,教授希望代码能够使用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.");
        }
    }
}

}

2 个答案:

答案 0 :(得分:2)

foreach可以像这样实现:

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

答案 1 :(得分:-1)

为什么你不使用LinQ?

var result = zips.Any(x=>x==correctZipCode);