LINQ query to match multiple words

I tried to solve this problem all day and did not find a solution that really works. When I search for some data, I want to filter the data based on a few words.

My input value is shared using the standard .Split function.

string[] searchstrings = MessageResult.Split(' '); 

I made a query (which obviously does not work properly) that tries to filter out all entries matching each line in searchstrings.

  var suggestions = (from a in query from w in searchstrings where a.Message.ToLower().Contains(w.ToLower()) select a).Distinct(); 

query is my variable that has all the data. How can I make this query actually match only records containing each row in searchstrings?

+7
source share
2 answers

I think the code below should solve your problem. It checks to see if all the words are in the search bar in query (a).

 var suggestions = (from a in query where searchstrings.All(word => a.ToLower().Contains(word.ToLower())) select a); 
+17
source
 var query = new string[] { "abc foo bar xyz john doe", "abc foo bar xyz doe", "hello world", "abc foo bar john doe", }; var searchstrings = new string[] { "abc", "foo", "john", "xyz", }; searchstrings = searchstrings.Select(x => x.ToLower()).ToArray(); var results = query.Select(x => x.ToLower()) .Where(x => searchstrings.All(y => x.Contains(y))); 

Note:
ToLower() runs outside the Where clause to save many calls to this method.

+16
source

All Articles