Question

Say I have a List<string> colors

List<string> colors = new List<string> { "red", "blue", "yellow"};

And I have a string that I want to search for.

string myString = "There is a red apple";

I want to check if myString contains anything from the list and return the search.

In this case, the program should find "red" and output "red" in the console.

I was able to check up to the contain part with Any(), but how can I return the result?

colors.Any(myString.Contains); //this only returns a bool I believe

Above method I use is half way there, how can I get the actual result?

--EDIT--

It's safe to assume that myString will at most contains only 1 from colors, and the match will always be whole-word match.

Was it helpful?

Solution

You can Split your string on white space and then use Enumerable.Intersect like:

var matching = colors.Intersect(myString.Split());

The above would return one item in matching, i.e. red

If you want case-insensitive then you can do:

var matching = colors.Intersect(myString.Split(), 
                                StringComparer.InvariantCultureIgnoreCase);

EDIT: If you are looking for Partial matching or multiple words matching then you can do:

List<string> colors = new List<string> { "red", "red apple", "yellow", "app" };
string myString = "There is a red apple";

var partialAllMatched =
    colors
       .Where(r => myString.IndexOf(r, StringComparison.InvariantCultureIgnoreCase) >=0);

This would return you:

red
red apple
app

OTHER TIPS

Or you can use :

var result = colors.FindAll(myString.Contains);

This returns a array with the output inside.

I would suggest you to try regex search on this one.

Build a search pattern with or operator and each color. Something like this "(red|blue|yellow)". Not sure if the pattern matches regex syntax but you get the idea.

Then in next step let regex use your pattern and try match it to provided text. In your case the text is myString.

Here is an example:

class TestRegularExpressions
{
    static void Main()
    {
        string[] sentences = 
        {
            "C# code",
            "Chapter 2: Writing Code",
            "Unicode",
            "no match here"
        };

        string sPattern = "code";

        foreach (string s in sentences)
        {
            System.Console.Write("{0,24}", s);

            if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
            {
                System.Console.WriteLine("  (match for '{0}' found)", sPattern);
            }
            else
            {
                System.Console.WriteLine();
            }
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();

    }
}
/* Output:
           C# code  (match for 'code' found)
           Chapter 2: Writing Code  (match for 'code' found)
           Unicode  (match for 'code' found)
           no match here
*/

Didn't see the use of LINQ Enumerable.Where, so here it is:

var colors = new[] {"red", "blue", "white", "black"};
const string str = "There is a red apple with black rocket.";

var foundWords = colors.Where(str.Contains).ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top