如何使用List的IndexOf()方法

发布于 2024-08-08 15:55:26 字数 324 浏览 1 评论 0原文

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

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

我想找到 employeeList.LastName == "Something" 的索引

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

绝不放开 2024-08-15 15:55:26
int index = employeeList.FindIndex(employee => employee.LastName.Equals(somename, StringComparison.Ordinal));

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

int index = employeeList.FindIndex(
    delegate(Employee employee)
    {
        return employee.LastName.Equals(somename, StringComparison.Ordinal);
    });
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);
    });
梦幻的味道 2024-08-15 15:55:26
public int FindIndex(Predicate<T> match);

使用 lambda:

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

注意:

// Returns:
//     The zero-based index of the first occurrence of an element
//     that matches the conditions defined by match, if found; 
//     otherwise, –1.
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.
所谓喜欢 2024-08-15 15:55:26

您可以通过覆盖 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;
        }
    }

you can do this through override Equals method

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;
        }
    }
独行侠 2024-08-15 15:55:26

抱歉,还有一个很好的措施:)

int index = employees.FindIndex(
      delegate(Employee employee)
        {
           return employee.LastName == "Something";
        });

编辑: - .NET 2.0 项目中的完整示例。

class Program
{
    class Employee { public string LastName { get; set; } }
    static void Main(string[] args)
    {
        List<Employee> employeeList = new List<Employee>();
        employeeList.Add(new Employee(){LastName="Something"});
        employeeList.Add(new Employee(){LastName="Something Else"});
        int index = employeeList.FindIndex(delegate(Employee employee) 
                           { return employee.LastName.Equals("Something"); });
        Console.WriteLine("Index:{0}", index);
        Console.ReadKey();
    }
}

Sorry, one more for good measure :)

int index = employees.FindIndex(
      delegate(Employee employee)
        {
           return employee.LastName == "Something";
        });

Edit: - Full Example in .NET 2.0 Project.

class Program
{
    class Employee { public string LastName { get; set; } }
    static void Main(string[] args)
    {
        List<Employee> employeeList = new List<Employee>();
        employeeList.Add(new Employee(){LastName="Something"});
        employeeList.Add(new Employee(){LastName="Something Else"});
        int index = employeeList.FindIndex(delegate(Employee employee) 
                           { return employee.LastName.Equals("Something"); });
        Console.WriteLine("Index:{0}", index);
        Console.ReadKey();
    }
}
栀子花开つ 2024-08-15 15:55:26

答案是让那些来这里的人知道为什么IndexOf()
不起作用。

您的类必须重写具有以下声明的对象Equals方法。

public override bool Equals(object obj)

The answer is for those coming here to know why IndexOf()
doesn't work.

Your class must override Equals method of object possessing the following declaration.

public override bool Equals(object obj)
数理化全能战士 2024-08-15 15:55:26

我更喜欢这样

    private List<Person> persons = List<Person>();

            public PersonService()
            {
                persons = new List<Person>() { 
                    new Person { Id = 1, DOB = DateTime.Today, FirstName = "Pawan", LastName = "Shakya" },
                    new Person { Id = 2, DOB = DateTime.Today, FirstName = "Bibek", LastName = "Pandey" },
                    new Person { Id = 3, DOB = DateTime.Today, FirstName = "Shrestha", LastName = "Prami" },
                    new Person { Id = 4, DOB = DateTime.Today, FirstName = "Monika", LastName = "Pandey" },
                };
            }

public PersonRepository.Interface.Person GetPerson(string lastName)
        {
            return persons[persons.FindIndex(p=>p.LastName.Equals(lastName, StringComparison.OrdinalIgnoreCase))];
        }

I prefer like this

    private List<Person> persons = List<Person>();

            public PersonService()
            {
                persons = new List<Person>() { 
                    new Person { Id = 1, DOB = DateTime.Today, FirstName = "Pawan", LastName = "Shakya" },
                    new Person { Id = 2, DOB = DateTime.Today, FirstName = "Bibek", LastName = "Pandey" },
                    new Person { Id = 3, DOB = DateTime.Today, FirstName = "Shrestha", LastName = "Prami" },
                    new Person { Id = 4, DOB = DateTime.Today, FirstName = "Monika", LastName = "Pandey" },
                };
            }

public PersonRepository.Interface.Person GetPerson(string lastName)
        {
            return persons[persons.FindIndex(p=>p.LastName.Equals(lastName, StringComparison.OrdinalIgnoreCase))];
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文