Come utilizzare IndexOf () di List

StackOverflow https://stackoverflow.com/questions/1568593

  •  21-09-2019
  •  | 
  •  

Domanda

Tutti gli esempi che vedo di usare il metodo IndexOf() in List<T> sono di tipo stringa di base. Quello che voglio sapere è come restituire l'indice di un tipo di elenco che è un oggetto, sulla base di una delle variabili oggetto.

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

Voglio trovare l'indice dove employeeList.LastName == "Something"

È stato utile?

Soluzione

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

Modifica: Senza lambda per C # 2.0 (l'originale non usa LINQ o qualsiasi .NET 3+ caratteristiche, solo la sintassi lambda in C # 3.0):

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

Altri suggerimenti

public int FindIndex(Predicate<T> match);

Utilizzando lambda:

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

Nota:

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

è possibile farlo attraverso di override metodo 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;
        }
    }

Siamo spiacenti, più uno per buona misura:)

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

Modifica: -. Esempio completo in 2.0 Progetto NET

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();
    }
}

Io preferisco come questo

    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))];
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top