web-dev-qa-db-fra.com

Comment utiliser la méthode IndexOf () de List <object>

Tous les exemples d'utilisation de la méthode IndexOf() dans List<T> sont des types de chaîne de base. Ce que je veux savoir, c'est comment renvoyer l'index d'un type de liste qui est un objet, basé sur l'une des variables d'objet.

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

Je veux trouver l'index où employeeList.LastName == "Something"

44
omencat
int index = employeeList.FindIndex(employee => employee.LastName.Equals(somename, StringComparison.Ordinal));

Edit: Sans lambdas pour C # 2.0 (l’original n’utilise ni LINQ ni aucune fonctionnalité .NET 3+, seulement la syntaxe lambda en C # 3.0):

int index = employeeList.FindIndex(
    delegate(Employee employee)
    {
        return employee.LastName.Equals(somename, StringComparison.Ordinal);
    });
68
Sam Harwell
public int FindIndex(Predicate<T> match);

Utilisation de lambdas:

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

Remarque: 

// Returns:
//     The zero-based index of the first occurrence of an element
//     that matches the conditions defined by match, if found; 
//     otherwise, –1.
22
Chris

vous pouvez le faire en remplaçant la méthode 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;
        }
    }
9
Ahmed Said

Désolé, encore une bonne mesure :)

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

Edit: - Exemple complet dans un projet .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();
    }
}
4
Wil P

Je préfère comme ça 

    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))];
        }
0
PAWAN RAJ Shakya