Alternative to if, else if

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

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

    Func 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".

提交回复
热议问题