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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With