[英]How to use IndexOf() method of List<object>
我看到的在List<T>
中使用IndexOf()
方法的所有示例都是基本字符串類型。 我想知道的是如何根據對象變量之一返回作為對象的列表類型的索引。
List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee("First","Last",45.00));
我想找到employeeList.LastName == "Something"
的索引
int index = employeeList.FindIndex(employee => employee.LastName.Equals(somename, StringComparison.Ordinal));
編輯: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);
});
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.
你可以通過覆蓋 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;
}
}
對不起,再來一個好措施:)
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();
}
}
我更喜歡這樣
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))];
}
答案是讓那些來到這里知道為什么
IndexOf()
不起作用的人。
您的類必須覆蓋具有以下聲明的object
Equals
方法。
public override bool Equals(object obj)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.