Mauricio Camacho
Mauricio Camacho

Reputation: 35

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 (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;
}

Upvotes: 0

Views: 5952

Answers (4)

Stephen Kennedy
Stephen Kennedy

Reputation: 21548

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(). 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:

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

Switch:

switch(GetLast(Pac.Sku))

Upvotes: 3

AmirNorsou
AmirNorsou

Reputation: 1131

I think it's not a way! You can only use the 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";
}

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117064

You can get creative with a Func<string, string>[] like this:

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. Nice for creating configurable solutions.

You're also not limited to just using EndsWith - any condition can be used that suits the purpose.

Upvotes: 2

Ankit Vijay
Ankit Vijay

Reputation: 4108

You can use pattern matching feature of C# 7.0 to achieve this. 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;
}

Upvotes: 3

Related Questions