2015-11-18 120 views
1

所以我有这段代码工作正常,我的任务如何教授希望代码与foreach声明一起工作。唯一能让它工作的方法是使用for循环。任何人都知道如何将for循环转换为foreach语句?转换为循环为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."); 
     } 
    } 
} 

}

+4

喜欢,为什么这个标签为'php'? –

+1

'foreach(拉链变量项){if(correctZipCode == item)...}'?顺便说一下,整数_不能有前导零。所以他们实际上是'7950,7840'等。 –

+4

或者只是Linq的一行'bool found = zips.Any(zip => zip == correctZipCode)' – juharr

回答

2

一个foreach可以这样实现:

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

你为什么不使用LINQ?

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

我同意,但它看起来像问一个关于使用'foreach'的具体例子。 –

+0

我犯了一个错误,下次我会添加评论。谢谢 –