檢查值是否在陣列中的 C# 程式
使用 Array.Exists 方法來檢查值是否在陣列中。
設定一個字串陣列 −
string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger" };
假設你需要在陣列中查詢值“keyboard”。為此,請使用 Array.Exists() −
Array.Exists(strArray, ele => ele == "keyboard");
如果元素存在,則返回真值,如下所示 −
示例
using System; using System.Text; public class Demo { public static void Main() { string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger" }; bool res1 = Array.Exists(strArray, ele => ele == "harddisk"); Console.WriteLine(res1); bool res2 = Array.Exists(strArray, ele => ele == "keyboard"); Console.WriteLine(res2); } }
輸出
False True
廣告