Reputation: 1622
I have a following array. I would like to find the index of the array which has M in the list so it should give me 2.
Array List
0 - > B, P , C
1 - > U, O, L
2 - > I, N, M
List<string>[] final = new List<string>[3];
I tried the following:
Array.IndexOf(final,"M")
But it does not work and it returns - 1 because second parameter is a list. Please do not use Linq
Upvotes: 1
Views: 66
Reputation:
Keep in mind that you have a List<string>
at each index of the array named final, so you just can't use Array.IndexOf
, you have to search for the Key separately at every index. Following code is the working example of what you want to achieve:
public static int SearchKey(List<string>[] array, string key)
{
int index = 0;
foreach(List<String> i in array)
{
if(i.Contains(key))
{
return index;
}
index++;
}
return -1;
}
Upvotes: 0
Reputation: 81573
Just put some alternatives, if you wanted to ditch the array you could achieve the following with standard Linq methods
var final = new List<List<string>>();
var item = final.FirstOrDefault(x => x.Contains("M"));
// do stuff with item result
var index = final.FindIndex(x => x.Contains("M"));
// do stuff with the index
Upvotes: 0
Reputation: 18163
Since your "item to search" is a sub item of the list, you would first need to search each list.This can be done with Linq. Combining the result of Linq Query with Array.IndexOf, you can find the result as
var result = Array.IndexOf(final,final.FirstOrDefault(x => x.Contains(searchString)));
Upvotes: 0
Reputation: 5185
Array.IndexOf
will traverse the one dimensional array and never find the search string
since it will be comparing it to List<string>
. You will have to traverse through the list of strings
in you array:
public static int FindLetter(IList<string>[] arr, string search)
{
for(int i = 0; i < arr.Length; ++i)
{
if(arr[i].Contains(search))
{
return i;
}
}
return -1;
}
Upvotes: 1