I was responding to a challenge to write C# code taking a if else statement and converting it to a Select statement with all the same outcome. Here is the if else code;
// SKU = Stock Keeping Unit.
// SKU value format: <product #>-<2-letter color code>-<size code>
string sku = "01-MN-L";
string[] product = sku.Split('-');
string type = "";
string color = "";
string size = "";
if (product[0] == "01")
{
type = "Sweat shirt";
} else if (product[0] == "02")
{
type = "T-Shirt";
} else if (product[0] == "03")
{
type = "Sweat pants";
}
else
{
type = "Other";
}
if (product[1] == "BL")
{
color = "Black";
} else if (product[1] == "MN")
{
color = "Maroon";
} else
{
color = "White";
}
if (product[2] == "S")
{
size = "Small";
} else if (product[2] == "M")
{
size = "Medium";
} else if (product[2] == "L")
{
size = "Large";
} else
{
size = "One Size Fits All";
}
Console.WriteLine($"Product: {size} {color} {type}");
This is my attempt at the problem and if works with the exception, that I can't handle the else part of the code which would require more than one default: statement in the Switch statement.
using System.Drawing;
string color = "";
string type = "";
string size = "";
string sku = "02-BK-R";
string[] product = sku.Split('-');
int skuPart = product.Length;
foreach (string productPart in product)
{
switch (productPart)
{
case "01":
type = "Sweat Shirt";
break;
case "02":
type = "T-Shirt ";
break;
case "03":
type = "Sweat Pants";
break;
case "MN":
color = "Maroon";
break;
case "BK":
color = "Black";
break;
case "S":
size = "Small";
break;
case "M":
size = "Medium";
break;
case "L":
size = "Large";
break;
default:
break;
}
}
Console.WriteLine($"Product: {size} {color} {type}");
In my opinion, the best solution is to write 3 switch statement for set values of type, color and size. this is how you can write your code:
I hope this solution can help you.