Alexander
Alexander

Reputation: 203

LINQ query to match multiple words

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?

Upvotes: 8

Views: 11854

Answers (2)

digEmAll
digEmAll

Reputation: 57220

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.

Upvotes: 19

Kasper Cottaar
Kasper Cottaar

Reputation: 462

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);

Upvotes: 19

Related Questions