I\'m doing an C# app where I use
if ((message.Contains(\"test\")))
{
Console.WriteLine(\"yes\");
} else if ((message.Contains(\"test2\"))) {
Console.W
Stegmenn nalied it for me but I had one change for when you have an IEnumerbale 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;
}
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;
}
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
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;
}
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.
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.