使用 array.exists 配合 string.equals 并指定 stringcomparison.ordinalignorecase 参数,可以忽略大小写逐个匹配候选值。该做法会遍历数组中的每个元素,只要有一个元素与目标字符串相等即返回 true,否则返回 false。

Array.IndexOf 在忽略大小写时如何定位索引?
Array.IndexOf 方法本身不支持直接传入比较器,因此需要结合 LINQ 的 Select 和 IndexOf 或者自定义循环来实现。更常见的做法是使用 Array.FindIndex,它允许传入一个 Predicate<t></t> 委托,从而在委托内部执行忽略大小写的比较。

using System;
using System.Linq;
public class Program
{
public static void Main()
{
string target = "Apple";
string[] candidates = { "banana", "APPLE", "cherry", "apple" };
// 使用 Array.FindIndex 进行忽略大小写的匹配
int index = Array.FindIndex(candidates, x => String.Equals(x, target, StringComparison.OrdinalIgnoreCase));
Console.WriteLine($"Found at index: {index}");
if (index != -1)
{
Console.WriteLine($"Matched value: {candidates[index]}");
}
}
}
运行上述代码,输出结果为:
Found at index: 1
Matched value: APPLE
这里 Array.FindIndex 遍历数组,当 x 为 "APPLE" 时,String.Equals 返回 true,因此返回索引 1。如果找不到匹配项,则返回 -1。
如何处理候选值为空或 null 的情况?
在使用 String.Equals 进行比较时,如果候选值 candidates[i] 为 null,直接调用 String.Equals(x, target, ...) 会导致 NullReferenceException。因此,需要在比较前检查候选值是否为 null 或空字符串。
using System;
public class Program
{
public static void Main()
{
string target = "Apple";
string[] candidates = { null, "banana", "APPLE", "", "cherry" };
int index = Array.FindIndex(candidates, x => !string.IsNullOrEmpty(x) && String.Equals(x, target, StringComparison.OrdinalIgnoreCase));
Console.WriteLine($"Found at index: {index}");
}
}
在上述代码中,!string.IsNullOrEmpty(x) 确保只有非空且非 null 的字符串才会进入 String.Equals 的比较逻辑。如果所有候选值都不匹配或为空,index 将为 -1。
基于程序中某个输入、条件或结果的具体问题
当候选数组中包含多个大小写不同的匹配项时,Array.FindIndex 和 Array.Exists 都会返回第一个匹配项的索引或 true。例如,如果候选数组为 { "apple", "APPLE" },目标为 "Apple",则 FindIndex 将返回 0,因为 "apple" 是第一个匹配的项。
这种行为符合预期,即优先返回最早出现的匹配项。如果需要获取所有匹配项,可以使用 LINQ 的 Where 方法过滤出所有符合条件的元素。


















