Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find array index by ignorecase [duplicate]

Tags:

arrays

string

c#

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?

like image 782
user1437001 Avatar asked Dec 01 '22 21:12

user1437001


2 Answers

By using FindIndex and a little lambda.

var ar = new[] { "hi", "Hello" };
var ix = Array.FindIndex(ar, p => p.Equals("hello", StringComparison.CurrentCultureIgnoreCase));
like image 196
xanatos Avatar answered Dec 22 '22 22:12

xanatos


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.

like image 37
Tisho Avatar answered Dec 22 '22 23:12

Tisho