有一些比这更快的方法来找到有条件的所有人吗?
if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(lastname) && !String.IsNullOrEmpty(phone))
{
List<Person> newList = List.FindAll(s => s.Name == name && s.Surname == lastname && s.Phone == phone);
}
else if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(lastname))
{
List<Person> newList = List.FindAll(s => s.Name == name && s.Surname == lastname);
}
等
答案 0 :(得分:7)
您的版本可能是运行时最快的选项。您创建的List<T>.FindAll
谓词效率很高,因为它检查的次数最少。
但是,您可以使用LINQ使代码更简单,更易于维护:
IEnumerable<Person> people = List; // Start with no filters
// Add filters - just chaining as needed
if (!string.IsNullOrWhitespace(name) && !string.IsNullOrWhitespace(lastname))
{
people = people.Where(s => s.Name == name && s.Surname == lastname);
if (!string.IsNullOrWhitespace(phone))
people = people.Where(s => s.Phone == phone);
}
//... Add as many as you want
List<Person> newList = people.ToList(); // Evaluate at the end
这将更加可维护,并且可能“足够快”,因为过滤通常不会在紧密循环中完成。
答案 1 :(得分:3)
我改写这种方式只是为了让它更容易阅读:
if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(lastname)) {
if (!String.IsNullOrEmpty(phone))
{
List<Person> newList = List.FindAll(s => s.Name == name && s.Surname == lastname && s.Phone == phone);
}
else
{
List<Person> newList = List.FindAll(s => s.Name == name && s.Surname == lastname);
}
}