Is there any way to make a case condition in a switch statement where you say if a string begins with something?
ex
Switch (mystring)
{
case("abc")://String begins with abc (abcd or abc1 or abcz or abc.. or abc will fall in this condition).
//Do Something
break;
default:
break;
}
UPDATE Other strings can be different length.
abc..
abczyv
dcs2.
qwerty
as...k
This question is related to
c#
string
switch-statement
case
Short answer: No.
The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.
So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.
Long answer #1 has been given by others.
Long answer #2:
Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.
Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.
The example you gave in your question would then look like this:
var commandList = new List<Command>() { new MyABCCommand() };
foreach (Command c in commandList)
{
if (c.Accept(mystring))
{
c.Execute(mystring);
break;
}
}
class MyABCCommand : Command
{
override bool Accept(string mystring)
{
return mystring.StartsWith("abc");
}
}
This is now possible with C# 7.0's pattern matching. For example:
var myString = "abcDEF";
switch(myString)
{
case string x when x.StartsWith("abc"):
//Do something here
break;
}
In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".
But before the switch statement you need to ensure that your mystring is atleast 3 in length.
If the problem domain has some kind of string header concept, this could be modelled as an enum.
switch(GetStringHeader(s))
{
case StringHeader.ABC: ...
case StringHeader.QWERTY: ...
...
}
StringHeader GetStringHeader(string s)
{
if (s.StartsWith("ABC")) return StringHeader.ABC;
...
}
enum StringHeader { ABC, QWERTY, ... }
If all the cases have the same length you can use
switch (mystring.SubString(0,Math.Min(len, mystring.Length)))
.
Another option is to have a function that will return categoryId based on the string and switch on the id.
Try this and tell my if it works hope it help you:
string value = Convert.ToString(Console.ReadLine());
Switch(value)
{
Case "abc":
break;
default:
break;
}
Source: Stackoverflow.com