How to use IndexOf() method of List<object>

omencat picture omencat · Oct 14, 2009 · Viewed 96k times · Source

All the examples I see of using the IndexOf() method in List<T> are of basic string types. What I want to know is how to return the index of a list type that is an object, based on one of the object variables.

List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee("First","Last",45.00));

I want to find the index where employeeList.LastName == "Something"

Answer

Sam Harwell picture Sam Harwell · Oct 14, 2009
int index = employeeList.FindIndex(employee => employee.LastName.Equals(somename, StringComparison.Ordinal));

Edit: Without lambdas for C# 2.0 (the original doesn't use LINQ or any .NET 3+ features, just the lambda syntax in C# 3.0):

int index = employeeList.FindIndex(
    delegate(Employee employee)
    {
        return employee.LastName.Equals(somename, StringComparison.Ordinal);
    });