gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:19:43 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com