List : How to get the index number of a particular element?

I search inside a list.
I get the item or element
How to know/get the location index number?

foreach (DataObject objectElement in database.dataListObject)
{
    if (objectElement.data.Contains(theWordToSearch))
    {
        //int index = DataObject.IndexOf(objectElement); <----------- ???
    }
}

Don’t use foreach.

Instead use for (i = 0; i < MyList.Count; i++) to get the index, and then use that index to dereference each item as you iterate.

3 Likes

yes, that was a stupid questio and a nice answer thx

2 Likes

If you prefer foreach, you’d do it like this

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
}

Rather than writing your own loop, you could also use the library function FindIndex.

1 Like

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. :stuck_out_tongue:

1 Like

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.

1 Like

why not to use foreach, please elaborate a bit

Did you even read the original question (and the message subject title)from three years ago before you came in necro-posting?

I’ll quote it here for you.

There are other reasons, such as changing the collection as you iterate it, which is NOT allowed with foreach

2 Likes

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 :slight_smile:

2 Likes