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

我试图只从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"


凤凰求蛊
浏览 160回答 1
1回答

翻翻过去那场雪

如果你想改变或进入和逻辑,所有你需要做的是改变WordsList.Any成WordsList.All条件:&nbsp;var records = SentencesList&nbsp; &nbsp;.Where(x => WordsList.All(y => x.Description.Contains(y)))&nbsp; &nbsp;.ToList();&nbsp;现在,我们希望所有的话中WordsList是在x
打开App,查看更多内容
随时随地看视频慕课网APP