List <>. FindAll with multiple conditions

Is there a faster method than this to find all people with certain 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); } 

and etc.

+4
source share
2 answers

Your version is most likely the fastest runtime option. The List<T>.FindAll you created is effective because it performs minimal checks.

However, you can use LINQ to make the code simpler and easier to maintain:

 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 much more convenient and probably โ€œfast enoughโ€ because filtering is usually not performed in a narrow loop.

+7
source

I would rewrite this method 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); } } 
+3
source

Source: https://habr.com/ru/post/1490532/


All Articles