C#使用foreach語句搜索數組元素的方法
更新時間:2015年04月10日 12:27:47 作者:heishui
這篇文章主要介紹了C#使用foreach語句搜索數組元素的方法,涉及C#使用foreach語句遍歷數組實現搜索功能的技巧,非常具有實用價值,需要的朋友可以參考下
本文實例講述了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#程序設計有所幫助。
相關文章
C#中在WebClient中使用post發(fā)送數據實現方法
這篇文章主要介紹了C#中在WebClient中使用post發(fā)送數據實現方法,需要的朋友可以參考下2014-08-08

