c# - List<>.FindAll 条件很少

标签 c#

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

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/

相关文章:

c# - 索引对象的哈希函数

c# - 在不使用 RouteAttribute 的情况下使用 ApiControllerAttribute

c# - 使用 Visual Studio 和 .NET Framework 进行多目标构建

c# - 我的 c# bin 文件夹中的 vshost 文件是什么?

c# - 为什么我的 WeakReference 示例不起作用?

c# - 决议免费申请

c# - 绑定(bind)到 Monotouch 中的第 3 方库 - 映射 uint8_t * 和 uint8_t **

c# - Linq where element.equals 一个数组

c# - 使用 LinQ 创建表时无法确定...的 SQL 类型

c# - 从 View 获取 List<ViewModel> 到 Controller