Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<>.FindAll with few conditions

Tags:

c#

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.

like image 739
user1638121 Avatar asked Dec 26 '22 00:12

user1638121


2 Answers

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.

like image 193
Reed Copsey Avatar answered Jan 13 '23 06:01

Reed Copsey


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);
     }
}
like image 21
JB King Avatar answered Jan 13 '23 07:01

JB King