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"
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); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With