August 2, 2021

soltveit.org

..Geekish..

C# return index of a object in a List

C# return index of a object

How to return the index of a list type that is an object in C#. Most examples only shows simple string types when they show how to find the index in a List. What if you have an List of class objects? Well, lets look at how we can use C# return index of a object in a List.

Create a simple Address Class

We will use a simple Address class to demostrate how to find an specific object in a list.

class AddressBook
{
    public string name;
    public string address;
    public AddressBook(string name, string address)
    {
        this.name = 
        this.address = address;
    }
}

A little test program

Let’s create a list, add some names and address. Then we will try to search for the index for some addresses. It is a simple address program to save your friends addresses.

static void Main(string[] args)
{
    List<AddressBook> book = new List<AddressBook>();

    // Add your friends
    book.Add(new AddressBook("Joe Biden", "White House"));
    book.Add(new AddressBook("Vladimir Putin", "Putins Palace"));
    book.Add(new AddressBook("Boris Johnson", "10 Downing Street"));

    // List their address to verify the list is ok
    foreach(var item in book)
    {
        WriteLine(item.address);
    }

    // Boris Johnsons is not a friend anymore, so we decide to remove him
    int index = book.FindIndex(
        delegate (AddressBook book)
        {
            return book.address.Equals("10 Downing Street");
        }
    );
    book.RemoveAt(index);

    // List to verify Boris Johnson was removed from our list
    foreach(var item in book)
    {
        WriteLine(item.address);
    }
}

This example shows how you find the index of an object based on the property “Address”. You could of course use the “Name” instead. It would make more sense here since we are removing an person from an address book. Read more about delegates on docs page.

Read about install Netcore on Debian.