Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign certain integer a value depending on string value in c#

Tags:

c#

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;
}
like image 873
BringQBasicBack Avatar asked Feb 19 '26 17:02

BringQBasicBack


1 Answers

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.

like image 192
BradleyDotNET Avatar answered Feb 21 '26 07:02

BradleyDotNET



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!