Alternative to if, else if

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

    Since you seem to need to search for the key before returning the value a Dictionary is the right way to go, but you will need to loop over it.

    // dictionary to hold mappings
    Dictionary mapping = new Dictionary();
    // add your mappings here
    // loop over the keys
    foreach (KeyValuePair item in mapping)
    {
        // return value if key found
        if(txtvar.BillText.IndexOf(item.Key) > -1) {
            return item.Value;
        }
    }
    

    EDIT: If you wish to have control over the order in which elemnts are evaluated, use an OrderedDictionary and add the elements in the order in which you want them evaluated.

提交回复
热议问题