3

Suppose I have 3 integers all declared as

int Y = 0;
int N = 0;
int U = 0;

From there I grab 2 values from a stored procedure (one string and 1 integer).
The string returns either Y,N,U
The integer returns a count of the people attending.

string test = dr["ATTEND_CDE"].ToString();
int test2 = int.Parse(dr["COUNT"].ToString());

Is there a better way to assign the corresponding integer the count other than:

if (test == "Y")
{
    Y = test2;
}
else if (test == "N")
{
    N = test2;
}
else if (test == "U")
{
    U = test2;
}
1
  • Just a side note: get rid of those "test" variable names before it's too late, they make the code harder to understand. Commented Aug 19, 2015 at 17:59

3 Answers 3

8

What you really have here is a mapping between a string ("Y", "N", or "U") and an int.

This is a perfect use case for a Dictionary (C# 6 syntax follows):

Dictionary<string, int> myValues = new Dictionary<string, int>()
{
    ["Y"] = 0,
    ["N"] = 0,
    ["U"] = 0
};

//usage
myValues[stringFromDatabase] = valueFromDatabase;

Note that this will throw (which is probably what you want) if the value from the database is junk.

Sign up to request clarification or add additional context in comments.

4 Comments

You can do that in C# 3 too: { "Y", 0 },
@SLaks Yes, but since I used the C# 6 form (with the index notation) I wanted to call that out. The C# 3 syntax is also valid of course.
Thanks! Works perfect and looks a lot better than an if statement
@BringQBasicBack FWIW, its more efficient (O(1) vs (O(n)) too (not that you would notice unless there was a lot of these, but still....)
2

You can use a switch statement on strings. So for your example above,

switch(test)
{
    case "Y": Y = test2; break;
    case "N": N = test2; break;
    case "U": U = test2; break;
}

Comments

1

If you store Y, N, U as properties in a class then you can work with

If you use c# 6.0 then you can at least do something like

if(test.equals(nameof(y)))
{
     //...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.