Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#Linq测试字符串是否包含字符串列表的一部分_C#_Linq - Fatal编程技术网

使用C#Linq测试字符串是否包含字符串列表的一部分

使用C#Linq测试字符串是否包含字符串列表的一部分,c#,linq,C#,Linq,我有一个字符串列表,名为TheListOfFruits“apple”、“banana”、“peach” 我有一个名为fullstring=“thebasketofapples” 我想知道字符串的部分是否包含在ListofRuits中 现在,我是这样做的: foreach(string s in TheListOfFruits) { if (TheFullString.Contains(s) == true) { return; } } 因此,在本例中,“

我有一个字符串列表,名为
TheListOfFruits“apple”、“banana”、“peach”

我有一个名为
fullstring=“thebasketofapples”

我想知道字符串的部分是否包含在ListofRuits中

现在,我是这样做的:

foreach(string s in TheListOfFruits)
{
    if (TheFullString.Contains(s) == true)
    {
        return;
    }
}
因此,在本例中,
“thebasketofapples”
包含
“apple”

是否有一种很好的Linq方法来编写此代码?

如果元素满足条件,则返回true。此代码与您的代码等效:

if(TheListOfFruits.Any(s => TheFullString.Contains(s))
{
   return;
}

您可以使用linq和任何函数编写这样的代码

if (TheListOfFruits.Any(t => TheFullString.Contains(t))) 
{
   return; 
}
答案如下:

var theListOfFruits = new List<string>() { "apple", "banana", "peach" };
        var theFullString = "thebasketofapples";

        bool result = theListOfFruits.Any(a => theFullString.Contains(a));
var theListOfFruits=newlist(){“苹果”、“香蕉”、“桃子”};
var theFullString=“thebasketofapples”;
bool result=theListOfFruits.Any(a=>theFullString.Contains(a));

Regex可能是一个更好的工具,这取决于所涉及的各种字符串。如果您需要区分“apple”和“apples”之间的区别该怎么办?可以缩短为:
if(TheListOfFruits.Any(TheFullString.Contains))return