How to make C# Switch Statement use IgnoreCase

后端 未结 10 1108
孤独总比滥情好
孤独总比滥情好 2020-11-27 16:56

If I have a switch-case statement where the object in the switch is string, is it possible to do an ignoreCase compare?

I have for instance:

string s =         


        
10条回答
  •  再見小時候
    2020-11-27 17:32

    Here's a solution that wraps @Magnus 's solution in a class:

    public class SwitchCaseIndependent : IEnumerable>
    {
        private readonly Dictionary _cases = new Dictionary(StringComparer.OrdinalIgnoreCase);
    
        public void Add(string theCase, Action theResult)
        {
            _cases.Add(theCase, theResult);
        }
    
        public Action this[string whichCase]
        {
            get
            {
                if (!_cases.ContainsKey(whichCase))
                {
                    throw new ArgumentException($"Error in SwitchCaseIndependent, \"{whichCase}\" is not a valid option");
                }
                //otherwise
                return _cases[whichCase];
            }
        }
    
        public IEnumerator> GetEnumerator()
        {
            return _cases.GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return _cases.GetEnumerator();
        }
    }
    

    Here's an example of using it in a simple Windows Form's app:

       var mySwitch = new SwitchCaseIndependent
       {
           {"hello", () => MessageBox.Show("hello")},
           {"Goodbye", () => MessageBox.Show("Goodbye")},
           {"SoLong", () => MessageBox.Show("SoLong")},
       };
       mySwitch["HELLO"]();
    

    If you use lambdas (like the example), you get closures which will capture your local variables (pretty close to the feeling you get from a switch statement).

    Since it uses a Dictionary under the covers, it gets O(1) behavior and doesn't rely on walking through the list of strings. Of course, you need to construct that dictionary, and that probably costs more.

    It would probably make sense to add a simple bool ContainsCase(string aCase) method that simply calls the dictionary's ContainsKey method.

提交回复
热议问题