4

有比这更快的方法来找到所有有条件的人吗?

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

等等

4

2 回答 2

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

这将更易于维护,并且可能“足够快”,因为过滤通常不会在紧密循环中完成。

于 2013-07-09T16:32:38.687 回答
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);
     }
}
于 2013-07-09T16:32:46.340 回答