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

I have a string

string str="hello";

This is my array

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

I need to find the index of “hello” from the array (Without Using a Loop)

So i have used

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

This returns -1 ,But i am expecting result as 1.

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

Hope someone can help. Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Beaware !! The Answer marked might have some problem , like

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 Indexofary = Array.FindIndex(array, t => t.IndexOf("hell", StringComparison.InvariantCultureIgnoreCase) >=0);

you will get result Indexofary = 0 instead of 4.

Instead of that use

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

to get proper result .

Rrgards
Bits

Method 2

Since you are looking for index. Try this way.

Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >=0);

Method 3

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

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

Method 4

var result = myarr.FindIndex(s => s.Equals(str, StringComparison.OrdinalIgnoreCase));

Method 5

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);
    }

Method 6

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);
}

Method 7

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!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x