简体   繁体   English

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

[英]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 方式来写这个?

Any returns true if an element satisfies a condition.如果元素满足条件,则Any返回 true。 This code is equivalent to yours:此代码等同于您的代码:

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

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.

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