Use string.Contains() with switch()

150,971

Solution 1

You can do the check at first and then use the switch as you like.

For example:

string str = "parameter"; // test1..test2..test3....

if (!message.Contains(str)) return ;

Then

switch(str)
{
  case "test1" : {} break;
  case "test2" : {} break;
  default : {} break;
}

Solution 2

Correct final syntax for [Mr. C]s answer.

With the release of VS2017RC and its C#7 support it works this way:

switch(message)
{
    case string a when a.Contains("test2"): return "no";
    case string b when b.Contains("test"): return "yes";
}

You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.

Solution 3

Nope, switch statement requires compile time constants. The statement message.Contains("test") can evaluate true or false depending on the message so it is not a constant thus cannot be used as a 'case' for switch statement.

Solution 4

If you just want to use switch/case, you can do something like this, pseudo-code:

    string message = "test of mine";
    string[] keys = new string[] {"test2",  "test"  };

    string sKeyResult = keys.FirstOrDefault<string>(s=>message.Contains(s));

    switch (sKeyResult)
    {
        case "test":
            Console.WriteLine("yes for test");
            break;
        case "test2":
            Console.WriteLine("yes for test2");
            break;
    }

But if the quantity of keys is a big, you can just replace it with dictionary, like this:

static Dictionary<string, string> dict = new Dictionary<string, string>();
static void Main(string[] args)
{
    string message = "test of mine";      

    // this happens only once, during initialization, this is just sample code
    dict.Add("test", "yes");
    dict.Add("test2", "yes2"); 


    string sKeyResult = dict.Keys.FirstOrDefault<string>(s=>message.Contains(s));

    Console.WriteLine(dict[sKeyResult]); //or `TryGetValue`... 
 }

Solution 5

This will work in C# 8 using a switch expresion

var message = "Some test message";

message = message switch
{
    string a when a.Contains("test") => "yes",
    string b when b.Contains("test2") => "yes for test2",
    _ => "nothing to say"
};

For further references https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression

Share:
150,971
pmerino
Author by

pmerino

Software developer with experience with Ruby, Ruby on Rails, Java, HTML, CSS, PHP, C#, JavaScript, Bash, Objective-C, MySQL, Postgres, SQLite, MongoDB, Redis as well as UNIX system administration.

Updated on March 24, 2021

Comments

  • pmerino
    pmerino about 3 years

    I'm doing an C# app where I use

    if ((message.Contains("test")))
    {
       Console.WriteLine("yes");
    } else if ((message.Contains("test2"))) {
       Console.WriteLine("yes for test2");
    }
    

    There would be any way to change to switch() the if() statements?

  • pmerino
    pmerino over 12 years
    So I only can use if()? That's pretty messy :(
  • Jon Skeet
    Jon Skeet over 12 years
    @zad0xsis: Do you have a lot of these? If so, you could potentially abstract the idea somewhat...
  • pmerino
    pmerino over 12 years
    yeah I've got a lot of if() :(
  • Mr. C
    Mr. C over 7 years
    It's worth noting - this will change with C# 7. Patterns can be used in case clauses. As of this writing, this feature is available in Visual Studio 15 Preview 4. blogs.msdn.microsoft.com/dotnet/2016/08/24/…
  • user9993
    user9993 about 7 years
    No, this does not work. Contains does not exist in the current context.
  • Phillip Quinlan
    Phillip Quinlan almost 6 years
    I removed <string> from string sKeyResult = keys.FirstOrDefault<string>(s=>message.Contains(s)); and still works fine.
  • Willy David Jr
    Willy David Jr over 5 years
    I cannot see your example on the link provided.
  • pogosama
    pogosama almost 5 years
    Does not work, you should test it first before sharing your answer. See Lakedaimon's solution for the correct syntax.
  • Jeroen Heier
    Jeroen Heier over 4 years
    Hi, welcome to stack overflow. For a useful answer explain why this is an answer to the question.
  • Admin
    Admin over 4 years
    in C# switch condition is not powerful as KOTLIN so if you want to implement String.contains() in condition state of switch I think we have to separate our condition in default part
  • Patrick
    Patrick about 4 years
    This is pretty close. Mr. C is correct in his answer. "This will work in C# 7" The syntax for this to work is slightly off though... Review Lakedaimon's answer for correct syntax.
  • Patrick
    Patrick about 4 years
    +1 This works perfectly now. And to anyone wondering you can access the value of the case via the "x" variable in this scenario.
  • Mark Monforti
    Mark Monforti about 4 years
    Thanks this worked perfectly for me, I had one small change that might help others that don't just have string message private static string GetRoles(IEnumerable<External.Role> roles) Here was my switch statement. switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
  • NovaDev
    NovaDev over 3 years
    I don't understand this answer.
  • Bob Lokerse
    Bob Lokerse about 3 years
    In the scenario of str = "test1,test2"; case "test1" will not work.
  • Yumi Koizumi
    Yumi Koizumi almost 3 years
    Also, you can use any var name-except-the one in the switch statement to evaluate. Then, you can refer to the original variable/expression in the code that follows.
  • David Mays
    David Mays over 2 years
    @Patrick, can you clarify what you mean by the "x" variable? Sorry I'm sure it's obvious.
  • David Mays
    David Mays over 2 years
    I feel so dumb asking about this simple answer, but isn't "break" also mandatory in C# case statements?
  • Lakedaimon
    Lakedaimon over 2 years
    In case statements you can leave the break if you use return.
  • GameSalutes
    GameSalutes over 2 years
    I find switch expressions a very strange syntax that is hard to remember. Always find myself looking it up if I haven't used it in a few months...
  • k3davis
    k3davis about 2 years
    If you don't need the value of var s (as you don't in your example) you can use var _ to discard it.