There's some faster method than this to find all person with some conditions?
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);
}
etc.
Your version is likely the fastest option at runtime. The List<T>.FindAll
predicate you created is efficient, since it does the fewest checks.
However, you could use LINQ to make the code simpler and more maintainable:
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
This will be far more maintainable, and likely be "fast enough", since filtering is typically not done in a tight loop.
I'd rewrite this way just to make it easier to read:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With