Alternative to if, else if

后端 未结 8 1062
后悔当初
后悔当初 2021-02-07 11:20

I have a lot of if, else if statements and I know there has to be a better way to do this but even after searching stackoverflow I\'m unsure of how to do so in my particular cas

8条回答
  •  梦谈多话
    2021-02-07 11:49

    To avoid the blatant Schlemiel the Painter's approach that looping over all the keys would involve: let's use regular expressions!

    // a dictionary that holds which bill text keyword maps to which provider
    static Dictionary BillTextToProvider = new Dictionary {
        {"SWGAS.COM", "Southwest Gas"},
        {"georgiapower.com", "Georgia Power"}
        // ...
    };
    
    // a regex that will match any of the keys of this dictionary
    // i.e. any of the bill text keywords
    static Regex BillTextRegex = new Regex(
        string.Join("|", // to alternate between the keywords
                    from key in BillTextToProvider.Keys // grab the keywords
                    select Regex.Escape(key))); // escape any special characters in them
    
    /// If any of the bill text keywords is found, return the corresponding provider.
    /// Otherwise, return null.
    string GetProvider(string billText) 
    {
        var match = BillTextRegex.Match(billText);
        if (match.Success) 
            // the Value of the match will be the found substring
            return BillTextToProvider[match.Value];
        else return null;
    }
    
    // Your original code now reduces to:
    
    var provider = GetProvider(txtvar.BillText);
    // the if is be unnecessary if txtvar.Provider should be null in case it can't be 
    // determined
    if (provider != null) 
        txtvar.Provider = provider;
    

    Making this case-insensitive is a trivial exercise for the reader.

    All that said, this does not even pretend to impose an order on which keywords to look for first - it will find the match that's located earliest in the string. (And then the one that occurs first in the RE.) You do however mention that you're searching through largeish texts; if .NET's RE implementation is at all good this should perform considerably better than 200 naive string searches. (By only making one pass through the string, and maybe a little by merging common prefixes in the compiled RE.)

    If ordering is important to you, you might want to consider looking for an implementation of a better string search algorithm than .NET uses. (Like a variant of Boyer-Moore.)

提交回复
热议问题