How to add a case-insensitive option to Array.IndexOf

22.1k views Asked by At

I have a string:

string str = "hello";

And an array:

string[] myarr = new string[] {"good", "Hello", "this", "new"};

I need to get the index of ("Hello") from the array when comparing with my string ("hello") (without using a loop).

I have tried:

int index = Array.IndexOf(myarr, str);

This returns -1, because of the capital "H", but I want a result of 1.

I have even tried with StringComparer.OrdinalIgnoreCase but no avail.

7

There are 7 answers

1
Shankar Narayana Damodaran On BEST ANSWER

Since you are looking for index. Try this way.

Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >=0);
0
Jason Meckley On
var result = myarr.FindIndex(s => s.Equals(str, StringComparison.OrdinalIgnoreCase));
0
doogle On

Array.IndexOf calls the default "Equals" method which is case-sensitive. Try this:

Array.FindIndex(myarr, t => t.Equals(str, StringComparison.InvariantCultureIgnoreCase))
1
BitsMax On

Beaware!!
The answer marked as a solution might have some problem, like with:

string array[] = {"hello", "hi", "bye" , "welcome" , "hell"}

If you use the same method (as described in the answer) to find the index of word "hell":

int indexOfArray = Array.FindIndex(array, t => t.IndexOf("hell", StringComparison.InvariantCultureIgnoreCase) >= 0);

you will get the result indexOfArray = 0 instead of 4.

Instead use:

Array.FindIndex(array, t => t.Equals("hell", StringComparison.InvariantCultureIgnoreCase));

to get a proper result.

0
Monkey in Pajamas On

I had a similar problem, I needed the index of the item but it had to be case insensitive, i looked around the web for a few minutes and found nothing, so I just wrote a small method to get it done, here is what I did:

private static int getCaseInvariantIndex(List<string> ItemsList, string searchItem)
{
    List<string> lowercaselist = new List<string>();

    foreach (string item in ItemsList)
    {
        lowercaselist.Add(item.ToLower());
    }

    return lowercaselist.IndexOf(searchItem.ToLower());
}

Add this code to the same file, and call it like this:

int index = getCaseInvariantIndexFromList(ListOfItems, itemToFind);

Hope this helps, good luck!

1
toddmo On

Since Array.IndexOf is generic, it makes sense to make a generic extension function:

public static int IndexOf<T>(this T[] source, T value)
{
  return IndexOf<T>(source, value, StringComparison.InvariantCultureIgnoreCase);
}

public static int IndexOf<T>(this T[] source, T value, StringComparison stringComparison)
{
  if (typeof(T) == typeof(string))
    return Array.FindIndex(source, m => m.ToString().Equals(value.ToString(), stringComparison));
  else
    return Array.IndexOf(source, value);
}
0
Maxim Kitsenko On

1) if you want to search only once and want to keep source array, you can use this:

        public static void example1()
        {
            string[] myarr = { "good", "Hello", "this", "new" };
            var str = "new";
            var res= Array.FindIndex(myarr, x=>string.Equals(x, str, StringComparison.InvariantCultureIgnoreCase));
        }

2) if you will search many times it will be better to use this:

public static void example1()
    {
        string[] myarr = {"good", "Hello", "this", "new"};
        var str = "new";
        var res = Array.IndexOf(Array.ConvertAll(myarr, ToStringlowerCase), str.ToLowerInvariant());
    }

3) the answer above is incorrect :

string array[] = {"hello", "hi", "bye" , "welcome" , "hell"}
Int Indexofary = Array.FindIndex(array, t => t.IndexOf("hell", StringComparison.InvariantCultureIgnoreCase) >=0);

will not work at all, because it searches not the string, but substring.

Algorithm iterates words in array, when 1st word "hello" taken, algorithm tries to find index of 'hell' and this index is 1. 1 is > then 0 and algorithm will be finished without going to other words.

If you don't want to search substrings but want to search strings, algorythm should be fixed. This algorithm can be fixed by adding check that substring starts from 1st char t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) == 0 and the length of the words equals str.Length == t.Length. Fixed:

        public static int example3()
    {
        string[] myarr = { "hHello", "hi", "bye", "welcome", "hell" };
        var str = "hell";
        return Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) == 0 && str.Length == t.Length);
    }