0

I have an array of search terms, and a setence. I need to test that the sentence contains all the search terms:

var searchTerms = "fox jumped".Split(' '); var sentence = "the quick brown fox jumped over the lazy dog".Split(' '); var test = sentence.Contains(searchTerms); 

I exptected test to be True -- howerver I get a compile error: 'string[]' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource)' has some invalid arguments

How should I test that sentence contains all the search terms?

2 Answers 2

3

You're trying to check whether there are any search terms that don't appear in the sentence:

if (!searchTerms.Except(sentence, StringComparer.CurrentCultureIgnoreCase).Any()) 
Sign up to request clarification or add additional context in comments.

5 Comments

Would searchTerms.Any(term => !sentence.Contains(term)) perform faster, or would they both compile to the same IL? (Gotta love IEnumerable)
@jbehren: That's much slower. It's ​O(n²), since it needs to loop over the other list every time.
It seems that .Except follows the same behavior pattern, except that it slims the lists down to distinct values first (which means it's iterating the lists MORE than the .Any method): hookedonlinq.com/ExceptOperator.ashx Basically, creating the set difference seems like it's going to follow the same path. (I say "seems" because I don't know the inner workings of LINQ)
@jbehren: Wrong. Except builds a HashSet, and is thus O(n).
That makes sense then. Thanks for taking the time :)
1

You could do this:

//test if all of the terms are in the sentence searchTerms.All(term => sentence.Contains(term)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.