Alternative to if, else if

后端 未结 8 1165
后悔当初
后悔当初 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 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.

提交回复
热议问题