如何从List <t>中检索项目,其中一个属性包含来自另一个列表的单词?

时间:2018-04-26 07:32:28

标签: c# linq lambda

我正在尝试仅检索List<T>中的项目,其中一个属性包含其他列表中的单词。

一旦它工作,我将使用我的实际数据库上的代码,但以下基本上是我想要做的。

List<string> WordsList = new List<string>();

WordsList.Add("THIS");
WordsList.Add("CAT");

List<Sentence> SentencesList = new List<Sentence>();

SentencesList.Add(new Sentence { Description = "THIS SENTENCE CONTAINS THE WORD DOG" });
SentencesList.Add(new Sentence { Description = "THIS SENTENCE CONTAINS THE WORD CAT" });
SentencesList.Add(new Sentence { Description = "THIS SENTENCE CONTAINS THE WORD DOG AND THE WORD CAT" });
SentencesList.Add(new Sentence { Description = "THIS SENTENCE CONTAINS NEITHER" });

现在我想从SentencesList中获取仅包含单词"THIS" "CAT&#34;

的项目
var records = SentencesList.Where(x => WordsList.Any(y => x.Description.Contains(y))).ToList();

以上代码检索所有商品,因为它们包含"THIS" "CAT"

1 个答案:

答案 0 :(得分:6)

如果您想将更改为逻辑,您只需将WordsList.Any更改为WordsList.All条件:

 var records = SentencesList
   .Where(x => WordsList.All(y => x.Description.Contains(y)))
   .ToList(); 

现在我们希望WordsList中的所有字词都在x