Use string.Contains() with switch()

C#StringIf StatementSwitch StatementContains

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 2 - C#

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 3 - C#

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 4 - C#

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

Solution 5 - C#

Simple yet efficient with c#

 string sri = "Naveen";
    switch (sri)
    {
        case var s when sri.Contains("ee"):
           Console.WriteLine("oops! worked...");
        break;
        case var s when sri.Contains("same"):
           Console.WriteLine("oops! Not found...");
        break;
    }

Solution 6 - C#

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 7 - C#

string message = "This is test1";
string[] switchStrings = { "TEST1", "TEST2" };
switch (switchStrings.FirstOrDefault<string>(s => message.ToUpper().Contains(s)))
{
    case "TEST1":
        //Do work
        break;
    case "TEST2":
        //Do work
        break;
    default:
        //Do work
        break; 
}

Solution 8 - C#

Some custom swtich can be created like this. Allows multiple case execution as well

public class ContainsSwitch
{

    List<ContainsSwitch> actionList = new List<ContainsSwitch>();
    public string Value { get; set; }
    public Action Action { get; set; }
    public bool SingleCaseExecution { get; set; }
    public void Perform( string target)
    {
        foreach (ContainsSwitch act in actionList)
        {
            if (target.Contains(act.Value))
            {
                act.Action();
                if(SingleCaseExecution)
                    break;
            }
        }
    }
    public void AddCase(string value, Action act)
    {
        actionList.Add(new ContainsSwitch() { Action = act, Value = value });
    }
}

Call like this

string m = "abc";
ContainsSwitch switchAction = new ContainsSwitch();
switchAction.SingleCaseExecution = true;
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });

switchAction.Perform(m);

Solution 9 - C#

Faced with this issue when determining an environment, I came up with the following one-liner:

string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));

That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null. This could easily be amended to return a different value.

It's not strictly a switch, more a cascading if statement but it's neat and it worked.

Solution 10 - C#

Stegmenn nalied it for me, but I had one change for when you have an IEnumerable instead of a string = message like in his example.

private static string GetRoles(IEnumerable<External.Role> roles)
{
    string[] switchStrings = { "Staff", "Board Member" };
    switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
    {
        case "Staff":
            roleNameValues += "Staff,";
            break;
        case "Board Member":
            roleNameValues += "Director,";
            break;
        default:
            break;
    }
}

Solution 11 - C#

This will work in C# 7. As of this writing, it has yet to be released. But if I understand this correctly, this code will work.

switch(message)
{
	case Contains("test"):
		Console.WriteLine("yes");
		break;
	case Contains("test2"):
		Console.WriteLine("yes for test2");
		break;
	default:
		Console.WriteLine("No matches found!");
}

Source: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

Solution 12 - C#

switch(message)
{
  case "test":
    Console.WriteLine("yes");
    break;                
  default:
    if (Contains("test2")) {
      Console.WriteLine("yes for test2");
    }
    break;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpmerinoView Question on Stackoverflow
Solution 1 - C#LakedaimonView Answer on Stackoverflow
Solution 2 - C#Teoman SoygulView Answer on Stackoverflow
Solution 3 - C#TigranView Answer on Stackoverflow
Solution 4 - C#Jesús JiménezView Answer on Stackoverflow
Solution 5 - C#NawinView Answer on Stackoverflow
Solution 6 - C#shenhengbinView Answer on Stackoverflow
Solution 7 - C#StegmannView Answer on Stackoverflow
Solution 8 - C#hungryMindView Answer on Stackoverflow
Solution 9 - C#0xFFView Answer on Stackoverflow
Solution 10 - C#Mark MonfortiView Answer on Stackoverflow
Solution 11 - C#Mr. CView Answer on Stackoverflow
Solution 12 - C#mehdi navabView Answer on Stackoverflow