Aelux Aelux - 1 year ago 102
C# Question

C# .IndexOf Arraylist returns -1

So i have a listbox setup that has a couple library names inside in when you launch the program and when one is selected so i did this to get the contents of the selected item.

string selectedItem = lstLibraries.SelectedItem.ToString();

Then i wanted to find out where in the arraylist i have set up that this string appears so i used this.

Libraries tempLibrary = (Libraries)LibrariesAndBooks[index];

As you can see in the screenshot below taken when the program had reached the error it is located at index[0] not -1 why is this happening?


Also hardcoding it to be 0 is not an option for what i need to do and if i made a silly mistake or my code makes you want to throw up thats fine because I'm only in my first year of university and hadn't done any code in 6th form for whatever reason so it's to be expected.

Answer Source

You are attempting to find a string in a collection of Libraries objects, which IndexOf cannot do. You will have to iterate over the collection and test the name of each item against selectedItem, in order to find the index yourself.

You might even consider writing a reusable method to make tasks like this easier, going forward. Something like:

    public static int FindIndex(IList collection, Func<object, bool> predicate)
        for (int i = 0; i < collection.Count; i++)
            if (predicate(collection[i]))
                return i;

        return -1;

This way, you can solve this problem easily going forward as such:

int index = FindIndex(LibrariesAndBooks, (item) => ((Libraries)item).Name == selectedItem)

The easier, non-reusable method would look like this:

int index = -1;
for (int i = 0; i < LibrariesAndBooks.Count; i++)
    // Retrieve & soft cast - if it is a book, candidateLibrary will be null
    Libaries candidateLibrary = LibrariesAndBooks[i] as Libraries;
    if (candidateLibrary == null)

    if (candidateLibrary.GetName() == selectedItem)
        index = i;

Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download