Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform switch statement if string is found

Tags:

c#

Below I've put together pseudo code of what I'm trying to do. I'm not entirely sure how to write this in C#. Is something like this possible, if so how can i do it. What i want to do is a run a function if the value returned is found.

pseudo code

string list = @"
This is a multiline statement
used for testing
"

foreach (var line in list)
{
    switch (line)
    {
        case (line.Contains("multiline")):
            Console.WriteLine("has A");
            break;
        case (line.Contains("testing")):
            Console.WriteLine("has B");
            break;
    }
}
like image 713
JokerMartini Avatar asked Dec 06 '25 00:12

JokerMartini


2 Answers

It is not possible. Using switch statement you just check the value of a given object. Try using a if:

foreach (var line in list)
{
    if (line.Contains("multiline"))
       Console.WriteLine("has A");
    else if (line.Contains("testing"))
       Console.WriteLine("has B");     
}

From the MSDN docs:

The switch statement is a control statement that selects a switch section to execute from a list of candidates.

The case statement is a compile time constant. The right use of a switch statement could be like this:

int caseSwitch = /* get a int value*/;
switch (caseSwitch)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        break;
    default:
        Console.WriteLine("Default case");
        break;
}
like image 116
Felipe Oriani Avatar answered Dec 07 '25 14:12

Felipe Oriani


What you are trying to do is called "pattern matching". C# doesn't yet support this, though it is being actively discussed as an addition to the next release, C# 7.

There are third party solutions that allow you to achieve what you are trying to do. My own Succinc<T> library for example, would allow you to write the code as:

string list = @"
This is a multiline statement
used for testing
";

foreach (var line in list)
{
    line.Match()
        .Where(l => l.contains("multiline").Do(l => Console.WriteLine("has A"))
        .Where(l => l.contains("testing").Do(l => Console.WriteLine("has B"))
        .IgnoreElse()
        .Exec();
}

It arguably leads to easier-to-follow, more functional, code than using a series of if's, though the trade-off is then in performance.

like image 20
David Arno Avatar answered Dec 07 '25 14:12

David Arno