Find ignorecase array index

Possible duplicate:
How to add case insensitive parameter in Array.IndexOf

int index1 = Array.IndexOf(myKeys, "foot"); 

Example: I have FOOT in my list of arrays, but it will return index1 = -1 .

How to find FOOT index ignoring case?

+4
source share
2 answers

Using FindIndex and a little lambda.

 var ar = new[] { "hi", "Hello" }; var ix = Array.FindIndex(ar, p => p.Equals("hello", StringComparison.CurrentCultureIgnoreCase)); 
+15
source

Using the 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 do BinarySearch in the array sorted :

 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 for large arrays, preferably static.

+1
source

All Articles