int index = 0;
foreach (DataObject objectElement in database.dataListObject)
{
if (objectElement.data.Contains(theWordToSearch))
{
//use index here for whatever you need it for
}
index++; //increment index for the next loop
}
Yeah I wrote the same thing (well I suggested IndexOf) and then deleted my post when I saw he has IndexOf already commented out in his/her code. Probably doesn’t want slight performance hit of calling IndexOf or FindIndex over and over every iteration of the loop.
Oh. If you’re using a loop to do something to every element of the list anyway and you just need to know the index number while you’re doing it, then you absolutely should use a for loop.
Use FindIndex if you only need to know the index of one object out of the entire list, and don’t care about the others.
Uhm, you do realise what the question of this thread was, right?
Of course if you only need a single index you “could” use IndexOf of the collection you’re iterating through (if that collection support it), however IndexOf itself has to iterate through the whole collection to find the index. So when using a normal for loop you already have the index at each iteration.
edit: Damn hadn’t refreshed the page so Kurt already answered