2011-02-11 49 views
0

我有一系列搜索项和一个句子。我需要测试的一句话包含了所有的搜索词:如何测试列表a中的所有项目都在列表中b

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

我exptected测试为True - howerver我得到一个编译错误: “字符串[]”不包含定义“包含”和最好的扩展方法重载'System.Linq.Queryable.Contains(System.Linq.IQueryable,TSource)'有一些无效参数

我应该如何测试该句子包含所有的搜索条件?

回答

3

你想检查是否有没有出现在句子中的任何搜索字词:

if (!searchTerms.Except(sentence, StringComparer.CurrentCultureIgnoreCase).Any()) 
+0

将searchTerms.Any(长期= >!sentence.contains(term))执行得更快,还是它们都会编译为相同的IL? (得爱IEnumerable) – jbehren 2011-02-11 15:02:36

+0

@jbehren:这太慢了。它是O(n²),因为它需要每次循环遍历另一个列表。 – SLaks 2011-02-11 15:03:01

1

你可以这样做:

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