[英]Using C# Linq to test if string contains parts of a list of string
I have a list of strings called TheListOfFruits "apple", "banana", "peach"
我有一个名为
TheListOfFruits "apple", "banana", "peach"
的字符串列表
I have a string called TheFullString = "thebasketofapples"
我有一个名为
TheFullString = "thebasketofapples"
的字符串
I want to know if TheFullString has parts of it contained in TheListOfFruits我想知道 TheFullString的一部分是否包含在 TheListOfFruits 中
For now, this is what I do:现在,这就是我所做的:
foreach(string s in TheListOfFruits)
{
if (TheFullString.Contains(s) == true)
{
return;
}
}
So in this case, "thebasketofapples"
contains "apple"
所以在这种情况下,
"thebasketofapples"
包含"apple"
Is there a nice Linq-way to write this?有没有一个很好的 Linq 方式来写这个?
You can write like this using linq using Any function你可以这样写 linq 使用 Any function
if (TheListOfFruits.Any(t => TheFullString.Contains(t)))
{
return;
}
Here is the answer:这是答案:
var theListOfFruits = new List<string>() { "apple", "banana", "peach" };
var theFullString = "thebasketofapples";
bool result = theListOfFruits.Any(a => theFullString.Contains(a));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.