Use string.Contains() with switch()

前端 未结 12 1994
抹茶落季
抹茶落季 2020-12-25 10:39

I\'m doing an C# app where I use

if ((message.Contains(\"test\")))
{
   Console.WriteLine(\"yes\");
} else if ((message.Contains(\"test2\"))) {
   Console.W         


        
相关标签:
12条回答
  • 2020-12-25 11:01

    Simple yet efficient with c#

     string sri = "Naveen";
        switch (sri)
        {
            case var s when sri.Contains("ee"):
               Console.WriteLine("oops! worked...");
            break;
            case var s when sri.Contains("same"):
               Console.WriteLine("oops! Not found...");
            break;
        }
    
    0 讨论(0)
  • If you just want to use switch/case, you can do something like this, pseudo-code:

        string message = "test of mine";
        string[] keys = new string[] {"test2",  "test"  };
    
        string sKeyResult = keys.FirstOrDefault<string>(s=>message.Contains(s));
    
        switch (sKeyResult)
        {
            case "test":
                Console.WriteLine("yes for test");
                break;
            case "test2":
                Console.WriteLine("yes for test2");
                break;
        }
    

    But if the quantity of keys is a big, you can just replace it with dictionary, like this:

    static Dictionary<string, string> dict = new Dictionary<string, string>();
    static void Main(string[] args)
    {
        string message = "test of mine";      
    
        // this happens only once, during initialization, this is just sample code
        dict.Add("test", "yes");
        dict.Add("test2", "yes2"); 
    
    
        string sKeyResult = dict.Keys.FirstOrDefault<string>(s=>message.Contains(s));
    
        Console.WriteLine(dict[sKeyResult]); //or `TryGetValue`... 
     }
    
    0 讨论(0)
  • 2020-12-25 11:02

    Some custom swtich can be created like this. Allows multiple case execution as well

    public class ContainsSwitch
    {
    
        List<ContainsSwitch> actionList = new List<ContainsSwitch>();
        public string Value { get; set; }
        public Action Action { get; set; }
        public bool SingleCaseExecution { get; set; }
        public void Perform( string target)
        {
            foreach (ContainsSwitch act in actionList)
            {
                if (target.Contains(act.Value))
                {
                    act.Action();
                    if(SingleCaseExecution)
                        break;
                }
            }
        }
        public void AddCase(string value, Action act)
        {
            actionList.Add(new ContainsSwitch() { Action = act, Value = value });
        }
    }
    

    Call like this

    string m = "abc";
    ContainsSwitch switchAction = new ContainsSwitch();
    switchAction.SingleCaseExecution = true;
    switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
    switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
    switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
    
    switchAction.Perform(m);
    
    0 讨论(0)
  • 2020-12-25 11:02
    switch(message)
    {
      case "test":
        Console.WriteLine("yes");
        break;                
      default:
        if (Contains("test2")) {
          Console.WriteLine("yes for test2");
        }
        break;
    }
    
    0 讨论(0)
  • 2020-12-25 11:03

    This will work in C# 7. As of this writing, it has yet to be released. But if I understand this correctly, this code will work.

    switch(message)
    {
        case Contains("test"):
            Console.WriteLine("yes");
            break;
        case Contains("test2"):
            Console.WriteLine("yes for test2");
            break;
        default:
            Console.WriteLine("No matches found!");
    }
    

    Source: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

    0 讨论(0)
  • 2020-12-25 11:07

    Correct final syntax for [Mr. C]s answer.

    With the release of VS2017RC and its C#7 support it works this way:

    switch(message)
    {
        case string a when a.Contains("test2"): return "no";
        case string b when b.Contains("test"): return "yes";
    }
    

    You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.

    0 讨论(0)
提交回复
热议问题