Search code examples
c#asp.netindexofignore-case

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


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.


Solution

  • Since you are looking for index. Try this way.

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