在 C# 中检查数组是否包含给定值
-
使用 C# 中的
Array.IndexOf()函数获取数组中元素的索引 -
使用 C# 中的
Array.FindIndex()函数获取数组中元素的索引 -
使用 C# 中的
Array.Exists()检查数组中的元素
本教程将介绍在 C# 中检查数组内部元素的方法。
使用 C# 中的 Array.IndexOf() 函数获取数组中元素的索引
C# 中的 Array.IndexOf(array, element) 函数获取数组 array 中元素 element 的索引。如果数组中不存在该元素,则返回 -1。
以下代码示例向我们展示了如何使用 C# 中的 Array.Indexof() 函数获取数组中元素的索引。
using System;
namespace check_element_in_array {
class Program {
static void Main(string[] args) {
string[] stringArray = { "value1", "value2", "value3", "value4" };
string value = "value3";
int index = Array.IndexOf(stringArray, value);
if (index > -1) {
Console.WriteLine("{0} found in the array at index {1}", value, index);
} else {
Console.WriteLine("Value not found");
}
}
}
}
输出:
value3 found in the array at index 2
我们使用 C# 中的 Array.IndexOf() 函数在数组 stringArray 中显示元素 value3 的索引。上面的代码在找到值的情况下显示元素的索引,在数组中找不到值的情况下显示 value not found。
使用 C# 中的 Array.FindIndex() 函数获取数组中元素的索引
如果元素存在于数组中,C# 中的 Array.FindIndex(array, pattern) 函数获取与数组 array 中的模式 pattern 相匹配的元素索引。如果数组中不存在该元素,则返回 -1。我们可以使用 lambda 表达式在 Array.FindIndex() 函数中指定 pattern 参数。
以下代码示例向我们展示了如何在 C# 中使用 Array.FindIndex() 函数和 lambda 表达式来获取数组中元素的索引。
using System;
namespace check_element_in_array {
class Program {
static void Main(string[] args) {
string[] stringArray = { "value1", "value2", "value3", "value4" };
string value = "value3";
var index = Array.FindIndex(stringArray, x => x == value);
if (index > -1) {
Console.WriteLine("{0} found in the array at index {1}", value, index);
} else {
Console.WriteLine("Value not found");
}
}
}
}
输出:
value3 found in the array at index 2
我们使用 C# 中的 Array.IndexOf() 函数在数组 stringArray 中显示元素 value3 的索引。上面的代码在找到值的情况下显示元素的索引,在数组中找不到值的情况下显示 value not found。
使用 C# 中的 Array.Exists() 检查数组中的元素
如果只需要检查数组中是否存在某个元素,而又不关心该元素所在的数组的索引,则可以使用 Array.Exists() 函数,位于 C# 中。Array.Exists() 函数返回一个布尔值,如果该元素存在于数组中,则为 true;如果该元素不存在于数组中,则为 false。
以下代码示例向我们展示了如何使用 C# 中的 Array.Exists() 函数检查数组中的元素。
using System;
namespace check_element_in_array {
class Program {
static void Main(string[] args) {
string[] stringArray = { "value1", "value2", "value3", "value4" };
string value = "value3";
var check = Array.Exists(stringArray, x => x == value);
if (check == true) {
Console.WriteLine("{0} found in the array", value);
} else {
Console.WriteLine("Value not found");
}
}
}
}
输出:
value3 found in the array
在上面的代码中,我们使用 C# 中的 Array.Exists() 函数检查了 stringArray 数组中是否存在值 value3。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn