I want to do a switch case
over a List<string>
in C#.
Let's say I have the following list:
var myList = new List<string>(new string[] { "Apple", "Pear" });
Now I wanna check if Apple or Pear and then do something. In an if statement
it would look like this:
if (myList.Contains("Apple"))
//do something
else if (myList.Contains("Pear"))
//so some other thing
else
//throw error
Now how can I do this in an clean way as a switch statement
?
Stumbled across this and didn't really see anyone answer him. It is possible to do this as a switch statement, whether or not it "looks" better can be decided by the user.
var myList = new List<string> { "Apple", "Pear" };
switch (myList)
{
case var _ when myList.Contains("Apple"):
// do apple stuff
break;
case var _ when myList.Contains("Pear"):
// do pear stuff
break;
default:
throw new System.ArgumentException("Some error message", nameof(myList));
}
I don't think, your desired behaviour can be cleanly modeled with a switch. But to make it as managable and easy to add/change as possible, how about something like this:
var handlers = new[]
{
new Tuple<string, Action>("Apple", () => { /* Apple-thing */ }),
new Tuple<string, Action>("Pear", () => { /* Pear-thing */ }),
// add as many handlers as needed in proper sequence
};
var handled = false;
foreach (var handler in handlers)
{
if (myList.Contains(handler.Item1))
{
handler.Item2();
handled = true;
break;
}
}
if (!handled)
{
// throw error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With