Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

indexof

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"

like image 312
omencat Avatar asked Oct 14 '09 19:10

omencat


2 Answers

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);     }); 
like image 104
Sam Harwell Avatar answered Sep 22 '22 21:09

Sam Harwell


public int FindIndex(Predicate<T> match); 

Using lambdas:

employeeList.FindIndex(r => r.LastName.Equals("Something")); 

Note:

// Returns: //     The zero-based index of the first occurrence of an element //     that matches the conditions defined by match, if found;  //     otherwise, –1. 
like image 45
Chris Avatar answered Sep 19 '22 21:09

Chris