Can anyone suggest how this can be improved?
public IEnumerable<Person> FindPersons(string queryTerms)
{
if (queryTerms == null)
return new List<Person>();
var queryTermsList = queryTerms.Split(' ').ToList();
var first = queryTermsList.First();
queryTermsList.Remove(first);
var people = FindPerson(first);
foreach (var queryTerm in queryTermsList)
{
people = people.Intersect(FindPerson(queryTerm));
}
return people;
}
Basically what it does is searches for people that contain EVERY queryTerm within the queryTermList.
Because results have to contain ALL terms I used Intersect.
Because I was using intersect I had to do an initial search for the first query term outside the foreach loop so the intersect within the loop would have something to intersect with. Otherwise you’d obviously always get empty results.
This meant I then needed to remove the first query term from the list before entering the foreach loop.
Ok, so this works. It just seems there must be a more elegant way of writing this.
Any suggestions?
You can just start with the entire collection and intersect all of the terms with that: