C# Switch-case string starting with

2020-06-30 07:31发布

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

7条回答
该账号已被封号
2楼-- · 2020-06-30 08:09

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.

查看更多
登录 后发表回答