我试图仅从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的项目”

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


上面的代码检索所有项目,因为它们包含"THIS""CAT"

最佳答案

如果要更改逻辑,请把WordsList.Any更改为WordsList.All条件:

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


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

07-26 04:20