Check string to see if string exists inside string array

I have a generic list of strings: List listOfString = new List ();

Then I add 4 lines to this list:

        listOfString .Add("test1");
        listOfString .Add("test2");
        listOfString .Add("test3");
        listOfString .Add("test4");

      

I want to test validate a string variable if it contains any element in my string array.

I've seen the Anyone method described, but this doesn't compile in C #, can I only do this in a for loop?

Thanks,.

0


a source to share


3 answers


I think the question is more about testing if the string contains any elements of the array.

Should look like this in pseudocode (I'm not familiar with .Net)



function StringContainsAny(String toTest, List<String> tests)
{
    foreach( String test in tests )
    {
        if( toTest.Contains(test) )
        {
            return test;
        }
    }
    return null;
}

      

+1


a source


You can use Any function if you are using LINQ method extensions (.net 3.5). eg:

var foobar = "foobar";
new[] {"foo", "bar"}.Any(foobar.Contains);

      

but if you smash Any you will see it anyway.

public static bo

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (predicate == null)
    {
        throw Error.ArgumentNull("predicate");
    }
    foreach (TSource local in source)
    {
        if (predicate(local))
        {
            return true;
        }
    }
    return false;
}

      



So, if you don't want to use .net 3.5, the above function in .Net 2.0 would look like this:

public static class Utilities
{
    public delegate bool AnyPredicate<T>(T arg);
    public static bool Any<TSource>(IEnumerable<TSource> source, AnyPredicate<TSource> predicate)
    {
        if (source == null)
        {
            throw new ArgumentException("source");
        }
        if (predicate == null)
        {
            throw new ArgumentException("predicate");
        }
        foreach (TSource local in source)
        {
            if (predicate(local))
            {
                return true;
            }
        }
        return false;
    }
}

      

using:

    var foobarlist = new[]{"foo", "bar"};
    var foobar = "foobar";
    var containsfoobar = Utilities.Any(foobarlist, foobar.Contains);

      

I hope this helps.

+1


a source


If I understand your question correctly, you need the following:

    public static bool ContainsAnyElement(IList<string> l, string input)
    {
        foreach (var s in l)
        {
            if (l.Contains(s))
                return true;
        }
        return false;
    }

    // Usage

    IList<string> l = new List<string>() { "a", "b", "c" };

    string test = "my test string with aa bbb and cccc";

    Console.WriteLine(ContainsAnyElement(l, test));

      

0


a source







All Articles