Search code examples
c#visual-studio-2003

c# if contains AND/OR


Is there a variant of this?

if (blabla.Contains("I'm a noob") | blabla.Contains("sry") | blabla.Contains("I'm a noob "+"sry"))
    {
        //stuff
    }

like:

if (blabla.Contains("I'm a noob) and/or ("sry")
    {
        //stuff
    }

Help is appreciated!


Solution

  • As far as I'm aware, there are no built-in methods to do this. But with a little LINQ and extension methods, you can create your own methods that will check to see if a string contains any or all tokens:

    public static class ExtensionMethods{
        public static bool ContainsAny(this string s, params string[] tokens){
            return tokens.Any(t => s.Contains(t));
        }
    
        public static bool ContainsAll(this string s, params string[] tokens){
            return tokens.All(t => s.Contains(t));
        }
    }
    

    You could use it like this (remember, params arrays take a variable number of parameters, so you're not limited to just two like in my example):

    var str = "this is a string";
    Console.WriteLine(str.ContainsAny("this", "fake"));
    Console.WriteLine(str.ContainsAny("doesn't", "exist"));
    Console.WriteLine(str.ContainsAll("this", "is"));
    Console.WriteLine(str.ContainsAll("this", "fake"));
    

    Output:

    True
    False
    True
    False

    Edit:

    For the record, LINQ is not necessary. You could just as easily write them this way:

    public static class ExtensionMethods{
        public static bool ContainsAny(this string s, params string[] tokens){
            foreach(string token in tokens)
                if(s.Contains(token)) return true;
            return false;
        }
    
        public static bool ContainsAll(this string s, params string[] tokens){
            foreach(string token in tokens)
                if(!s.Contains(token)) return false;
            return true;
        }
    }