Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query to match multiple words

Tags:

c#

linq

I've been trying to solve this problem all day, and haven't found a solution that truly works. When I search for some data, I want to filter out the data based on multiple words.

My input value is split up by using the standard .Split-function.

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

I've made a query (which obviously doesn't work properly) that tries to filter out all the entries that matches every string 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 which has all the data. How can I make this query to actually only match out entries that includes every string in searchstrings?

like image 723
Alexander Avatar asked Jul 19 '12 12:07

Alexander


2 Answers

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() is performed outside the Where clause, to save a lot of calls to that method.

like image 177
digEmAll Avatar answered Oct 25 '22 03:10

digEmAll


I think code below should solve your problem. It checks if all words in searchstring are in a query (a).

var suggestions = (from a in query
                   where searchstrings.All(word => a.ToLower().Contains(word.ToLower()))
                   select a);
like image 23
Kasper Cottaar Avatar answered Oct 25 '22 04:10

Kasper Cottaar