Alternative to if, else if

后端 未结 8 1049
后悔当初
后悔当初 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 12:06

    One way of doing it (other answers show very valid options):

    void Main()
    {
        string input = "georgiapower.com";
        string output = null;
    
        // an array of string arrays...an array of Tuples would also work, 
        // or a List<T> with any two-member type, etc.
        var search = new []{
            new []{ "SWGAS.COM", "Southwest Gas"},
            new []{ "georgiapower.com", "Georgia Power"},
            new []{ "City of Austin", "City of Austin"}
        };
    
        for( int i = 0; i < search.Length; i++ ){
    
            // more complex search logic could go here (e.g. a regex)
            if( input.IndexOf( search[i][0] ) > -1 ){
                output = search[i][1];
                break;
            }
        }
    
        // (optional) check that a valid result was found.
        if( output == null ){
            throw new InvalidOperationException( "A match was not found." );
        }
    
        // Assign the result, output it, etc.
        Console.WriteLine( output );
    }
    

    The main thing to take out of this exercise is that creating a giant switch or if/else structure is not the best way to do it.

    0 讨论(0)
  • 2021-02-07 12:06

    There are several approaches to do this, but for the reason of simplicity, conditional operator may be a choice:

    Func<String, bool> contains=x => {
        return txtvar.BillText.IndexOf(x)>-1;
    };
    
    txtvar.Provider=
        contains("SWGAS.COM")?"Southwest Gas":
        contains("georgiapower.com")?"Georgia Power":
        contains("City of Austin")?"City of Austin":
        // more statements go here 
        // if none of these matched, txtvar.Provider is assigned to itself
        txtvar.Provider;
    

    Note the result is according to the more preceded condition which is met, so if txtvar.BillText="City of Austin georgiapower.com"; then the result would be "Georgia Power".

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