views:

1298

answers:

3

Hi ,

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

I then add 4 strings to this list:

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

I want to check check a string variable if it contains any element within my string array is present.

I have seen the 'Any' method described but this does not compile in C# can i do this only in a for loop?

Thanks,.

+1  A: 

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

Should look like this in pseudo-code (I'm not that familiar with .Net)

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

If I understand your question correctly, you need this:

    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));
bruno conde
+1  A: 

You could use the Any function if you use the LINQ Method extensions (.net 3.5). like this:

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

but if you dissasemble Any you'll see it's just a loop 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;
    }
}

usage:

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

I hope that helps.

Sven Hecht