伙计我知道这可能是一个天真的问题,但我得问。
我有一串字符串
List<string> lstPets = new List<string> { "dog", "cat","horse","parrot" };
一个字符串
string paragraph = "This is a test script to test whether a dog exists or not";
现在我必须编写一个linq查询来查找“paragrah”中是否出现“lstPets”。
提前致谢。 :)
答案 0 :(得分:4)
var lstPets = new List<string> { "dog", "cat","horse","parrot" };
string paragraph = "This is a test script to test whether a dog exists or not";
var containsAny = lstPets.Any(paragraph.Contains);
或者可能更宽容:
var containsAny = lstPets.Any(pet => paragraph.Contains(pet, StringComparison.OrdinalIgnoreCase));
答案 1 :(得分:0)
var sentenceQuery = from item in paragraph
let w = item .Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries)
where w.Distinct().Intersect(IsPets).Count() == IsPets.Count()
select item ;
foreach (string str in sentenceQuery)
{
Console.WriteLine(str);
}
答案 2 :(得分:0)
尝试代码
var countres = lstPets.Where(c => paragraph.Contains(c)).ToList().Count() > 0 ? true : false;