How to make C# Switch Statement use IgnoreCase

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

    An extension to the answer by @STLDeveloperA. A new way to do statement evaluation without multiple if statements as of c# 7 is using the pattern matching Switch statement, similar to the way @STLDeveloper though this way is switching on the variable being switched

    string houseName = "house";  // value to be tested
    string s;
    switch (houseName)
    {
        case var name when string.Equals(name, "Bungalow", StringComparison.InvariantCultureIgnoreCase): 
            s = "Single glazed";
        break;
    
        case var name when string.Equals(name, "Church", StringComparison.InvariantCultureIgnoreCase):
            s = "Stained glass";
            break;
            ...
        default:
            s = "No windows (cold or dark)";
            break;
    }
    

    The visual studio magazine has a nice article on pattern matching case blocks that might be worth a look.

提交回复
热议问题