如何使用List <object>的IndexOf()方法

ome*_*cat 46 c# list indexof

我在使用该IndexOf()方法时看到的所有示例List<T>都是基本字符串类型.我想知道的是如何根据一个对象变量返回作为对象的列表类型的索引.

List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee("First","Last",45.00));
Run Code Online (Sandbox Code Playgroud)

我想找到索引在哪里 employeeList.LastName == "Something"

Sam*_*ell 73

int index = employeeList.FindIndex(employee => employee.LastName.Equals(somename, StringComparison.Ordinal));
Run Code Online (Sandbox Code Playgroud)

编辑:没有用于C#2.0的lambdas(原始版本不使用LINQ或任何.NET 3+功能,只是C#3.0中的lambda语法):

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


小智 22

public int FindIndex(Predicate<T> match);
Run Code Online (Sandbox Code Playgroud)

使用lambdas:

employeeList.FindIndex(r => r.LastName.Equals("Something"));
Run Code Online (Sandbox Code Playgroud)

注意:

// Returns:
//     The zero-based index of the first occurrence of an element
//     that matches the conditions defined by match, if found; 
//     otherwise, –1.
Run Code Online (Sandbox Code Playgroud)


Ahm*_*aid 9

你可以通过覆盖Equals方法来做到这一点

class Employee
    {
        string _name;
        string _last;
        double _val;
        public Employee(string name, string last, double  val)
        {
            _name = name;
            _last = last;
            _val = val;
        }
        public override bool Equals(object obj)
        {
            Employee e = obj as Employee;
            return e._name == _name;
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是回答原始问题的唯一答案 - 如何对任何对象使用`IndexOf()`.其他人刚刚建议使用`FindIndex()`而不是......这没关系,但是这个答案应该得到更多的信任. (6认同)