C# 按ignorecase查找数组索引
可能重复:C# 按ignorecase查找数组索引,c#,arrays,string,C#,Arrays,String,可能重复: 例如,我的数组列表中有FOOT,但它将返回index1=-1的值 如何通过忽略大小写来查找foot的索引?使用FindIndex和一点lambda var ar = new[] { "hi", "Hello" }; var ix = Array.FindIndex(ar, p => p.Equals("hello", StringComparison.CurrentCultureIgnoreCase)); 使用i比较程序类: public class CaseInsensi
例如,我的数组列表中有
FOOT
,但它将返回index1=-1的值
如何通过忽略大小写来查找foot
的索引?使用FindIndex
和一点lambda
var ar = new[] { "hi", "Hello" };
var ix = Array.FindIndex(ar, p => p.Equals("hello", StringComparison.CurrentCultureIgnoreCase));
使用i比较程序
类:
public class CaseInsensitiveComp: IComparer<string>
{
private CaseInsensitiveComparer _comp = new CaseInsensitiveComparer();
public int Compare(string x, string y)
{
return _comp.Compare(x, y);
}
}
public class CaseInsensitiveComp:IComparer
{
私人案件不敏感比较人_comp=新案件不敏感比较人();
公共整数比较(字符串x、字符串y)
{
返回比较(x,y);
}
}
然后对排序后的数组执行二进制搜索:
var myKeys = new List<string>(){"boot", "FOOT", "rOOt"};
IComparer<string> comp = new CaseInsensitiveComp();
myKeys.Sort(comp);
int theIndex = myKeys.BinarySearch("foot", comp);
var myKeys=newlist(){“boot”、“FOOT”、“rOOt”};
IComparer comp=新的不区分大小写的comp();
myKeys.Sort(comp);
int theIndex=myKeys.BinarySearch(“foot”,comp);
通常在较大的阵列上最有效,最好是静态阵列
var myKeys = new List<string>(){"boot", "FOOT", "rOOt"};
IComparer<string> comp = new CaseInsensitiveComp();
myKeys.Sort(comp);
int theIndex = myKeys.BinarySearch("foot", comp);