简体   繁体   中英

Get every item in a list that contains every string in an other list

I have basically two string-lists and want to get the elements of the first list that contain every word of the second list.

List<Sentence> sentences = new List<Sentence> { many elements };

List<string> keyWords= new List<string>{"cat", "the", "house"};

class Sentence 
{
public string shortname {get; set; }
}

Now, how do I perform a contain-check for every element of the keyWords-List for a sentence? Something like

var found = sentences.Where(x => x.shortname.ContainsAll(keyWords)));

Try this:

var found = sentences.Where(x=> keyWords.All(y => x.shortname.Contains(y)));

The All method is used to filter out those sentences which contain all keywords from the list of keywords.

Use All

sentences.Where(x => keywords.All(k => x.shortname.Contains(k)));

If you find this to be a common search, you could create your own extension method

public static bool ContainsAll<T>(this IEnumerable<T> src, IEnumerable<T> target)
{
    return target.All(x => src.Contains(x));
}

This would allow you to write the code as you originall expressed it

sentences.Where(x => x.shortname.ContainsAll(keywords));
sentences.Where(s => keyWords.All(kw => s.shortname.Contains(kw)));

使用全部,仅当序列中的所有元素都满足条件时才返回true

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