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);
}
Array.FindIndex()
, due to usingSystem.String.IndexOf()
. To match the elements in full, use the analogousSystem.String.Equals()
overload, as shown in the other answers. – Kippie