Possible Duplicate:
How to add a case-insensitive option to Array.IndexOf
int index1 = Array.IndexOf(myKeys, "foot");
Example I have FOOT
in my array list, but it will return value of index1 = -1
.
How can I find index of foot
by ignoring the case?
By using FindIndex
and a little lambda.
var ar = new[] { "hi", "Hello" };
var ix = Array.FindIndex(ar, p => p.Equals("hello", StringComparison.CurrentCultureIgnoreCase));
Using an IComparer<string>
class:
public class CaseInsensitiveComp: IComparer<string>
{
private CaseInsensitiveComparer _comp = new CaseInsensitiveComparer();
public int Compare(string x, string y)
{
return _comp.Compare(x, y);
}
}
Then performing a BinarySearch on the sorted array:
var myKeys = new List<string>(){"boot", "FOOT", "rOOt"};
IComparer<string> comp = new CaseInsensitiveComp();
myKeys.Sort(comp);
int theIndex = myKeys.BinarySearch("foot", comp);
Usually most effective on bigger arrays, preferably static.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With