简体   繁体   English

C# Switch-case 字符串以

[英]C# Switch-case string end with

Is there any way to make a case condition in a switch statement where you say if a string end with something?有什么方法可以在 switch 语句中创建一个 case 条件,你说一个字符串是否以某物结尾?

switch (Pac.Sku)
{
    case "A":
        pacVM.Sucursal = "Managua";
        break;
    case "B":
        pacVM.Sucursal = "Masaya";
        break;
    case "C":
        pacVM.Sucursal = "Leon";
        break;
    default:
        pacVM.Sucursal = "N/A";
        break;
}

Get the last character of the string, and switch over the result:获取字符串的最后一个字符,并切换结果:

switch (Pac.Sku.Last())
{
    case 'A':
        pacVM.Sucursal = "Managua";
        break;

    case 'B':
        pacVM.Sucursal = "Masaya";
        break;

    case 'C':
        pacVM.Sucursal = "Leon";
        break;

    default:
        pacVM.Sucursal = "N/A";
        break;
}

If the string could be null or empty use something like this function instead of Last() .如果字符串可能为null或为空,请使用类似此函数的函数而不是Last() This function returns null if the string is null , null if the string is empty, and the last character of the string if it is not null or empty:该函数返回null字符串是否nullnull字符串是否为空,字符串的最后一个字符,如果它不是null或空:

char? GetLast(string s)
{
    return s?.Length > 0 ? s.Last() : (char?)null;
}

Switch:转变:

switch(GetLast(Pac.Sku))

You can usepattern matching feature of C# 7.0 to achieve this.您可以使用 C# 7.0 的模式匹配功能来实现这一点。 Here is a very basic example:这是一个非常基本的例子:

var t = "blah";

switch (t)
{
    case var a when t.EndsWith("bl"):
        Console.WriteLine("I'm not here");
        break;

    case var b when t.EndsWith("ah"):
        Console.WriteLine("I'm here");
        break;
}

You can get creative with a Func<string, string>[] like this:你可以像这样使用Func<string, string>[]来获得创意:

Func<string, string>[] cases = new Func<string, string>[]
{
    x => x.EndsWith("A") ? "Managua" : null,
    x => x.EndsWith("B") ? "Masaya" : null,
    x => x.EndsWith("C") ? "Leon" : null,
    x => "N/A",
};

Func<string, string> @switch = cases.Aggregate((x, y) => z => x(z) ?? y(z));

string result = @switch(Pac.Sku);

I have tested this with sample input that matches each of the cases and it works just fine.我已经使用与每种情况匹配的示例输入对此进行了测试,并且效果很好。

One significant advantage with this approach is that you can build the Func<string, string>[] at run-time.这种方法的一个显着优点是您可以在运行时构建Func<string, string>[] Nice for creating configurable solutions.非常适合创建可配置的解决方案。

You're also not limited to just using EndsWith - any condition can be used that suits the purpose.您也不仅限于使用EndsWith - 可以使用适合目的的任何条件。

I think it's not a way!我觉得不是办法! You can only use the if-else您只能使用 if-else

if (Pac.Sku.EndsWith("A") )
{
    pacVM.Sucursal= "Managua";
}
else if (Pac.Sku.EndsWith("B"))
{
    pacVM.Sucursal= "Masaya";
}
else if (Pac.Sku.EndsWith("C"))
{
    pacVM.Sucursal= "Leon";
}
else
{
    pacVM.Sucursal= "N/A";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM