How to make C# Switch Statement use IgnoreCase

后端 未结 10 1107
孤独总比滥情好
孤独总比滥情好 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:23

    One possible way would be to use an ignore case dictionary with an action delegate.

    string s = null;
    var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase)
    {
        {"house",  () => s = "window"},
        {"house2", () => s = "window2"}
    };
    
    dic["HouSe"]();
    

    // Note that the call doesn't return text, but only populates local variable s.
    // If you want to return the actual text, replace Action to Func and values in dictionary to something like () => "window2"

提交回复
热议问题