Using C# Linq to test if string contains parts of a list of string

Viewed 106

I have a list of strings called TheListOfFruits "apple", "banana", "peach"

I have a string called TheFullString = "thebasketofapples"

I want to know if TheFullString has parts of it contained in 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"

Is there a nice Linq-way to write this?

3 Answers

Any returns true if an element satisfies a condition. This code is equivalent to yours:

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

You can write like this using linq using 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));
Related