本文實例講述了C#使用foreach語句搜索數組元素的方法。分享給大家供大家參考。具體分析如下:
下面的代碼通過foreach語句對數組遍歷,然后對元素進行逐個比較的方法來查找數組中的元素
using System;public class Search { public static void Main() { int[] nums = new int[10]; int val; bool found = false; // give nums some values for(int i = 0; i < 10; i++) nums[i] = i; val = 5; // 通過foreach語句在nums數組中查找指定元素 foreach(int x in nums) { if(x == val) { found = true; break; } } if(found) Console.WriteLine("Value found!"); }}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答