Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch case over an List<string> in C#

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?


2 Answers

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));
}
like image 82
Alfreo Avatar answered Sep 17 '25 06:09

Alfreo


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
}
like image 34
Corak Avatar answered Sep 17 '25 07:09

Corak