有比这更快的方法来找到所有符合条件的人吗?
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);
}
等等
最佳答案
您的版本可能是运行时最快 选项。 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
这将更易于维护,并且可能“足够快”,因为过滤通常不会在紧密循环中完成。
关于c# - List<>.FindAll 条件很少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17553501/