tags:

views:

50

answers:

5

I will try to make this simple and quick.. I have never attempted this before so I am a little lost.. What I want to do is to have a variable string (op20) that has a value based on a condition that is met.. Perhaps there is an easier way to accomplish this... Example:

string op20A = "5";
string op20D = "19";
string op20C = "6";
string op20E = "14";
string op20J = "15";
string op20Y = "21";

string op20raw = "R288319"

if (op20raw == "R288319") string op20 = op20A;
if (op20raw == "R288320") string op20 = op20D;
if (op20raw == "R288321") string op20 = op20C;
etc etc
+1  A: 

Hi! I would suggest using a switch construct. See here for a reference:

http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx

It's always a good idea to have a default case, in case the variable you are testing is assigned something you hadn't explicitly set.

string op20A = "5";
string op20D = "19";
string op20C = "6";
string op20E = "14";
string op20J = "15";
string op20Y = "21";

string op20raw = "R288319"

// declare the string first
string op20;

// now assign it using a 'switch' statement
switch (op20raw)
{
    case "R288319":
        op20 = op20A;
        break;
    case "R288320":
        op20 = op20D;
        break;
    case "R288321":
        op20 = op20C;
        break;
    default:
        op20 = "something else";
        break;
}

Finally, your code would not compile because you were attempting to declare op20 three times: just declare it once then assign it as you please.

Hope that helps!

Kieren Johnstone
+1  A: 

I would suggest you use a Dictionary.

This will make your retrieval code simpler.

Moron
+2  A: 

Since you are branching your code based on a single variable value (op20raw) you can use the switch statement.

For instance:

string op20 = String.Empty;
switch(op20raw) { 
        case "R288319": 
          op20 = op20A;
          break; 
        case "R288320": 
          op20 = op20B; 
          break; 
        // and so on
        }

As an alternative you can create a Dictionary<string,string> where the keys are the possible values for the op20raw variable and the values are the corresponding values for the op20 variable. Then, simply get the proper value from the dictionary:

string a20 = myDictionary.ContainsKey(op20raw) ? myDictionary[op20raw] : String.Empty;
Hemme
+6  A: 

Your solution is nearly the best for just two or three conditions.

I would tend to prefer this if there are more than two or three:

var map = new Dictionary<string, string>() {
    { "R288319", op20A },
    { "R288320", op20D },
    { "R288321", op20C }
};

string op20 = map[op20raw]; // assuming no erroneous raw strings
mquander
A: 

You can use a switch statement:

switch(op20raw)
{
  case "R288319":
  op20 = op20A;
  break;
  case "R288320":
  op20 = op20D;
  break;
etc..
}
Jouke van der Maas