简体   繁体   中英

How do I retrieve items from a List<T> where one property contains exactly the words from another list?

I am trying to retrieve only the items from a List<T> where one of the properties contains the words from another list.

Once it works I will use the code on my actual database, but the below is basically what I want to do.

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" });

Now I want to get the items from SentencesList that contain only the words "THIS" and "CAT "

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

The above piece of code retrieves all items because they contain "THIS" or "CAT"

If you want to change or into and logic, all you have to do is to change WordsList.Any into WordsList.All condition:

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

Now we want all words in WordsList to be in x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM