Question Too many if statements…

Lep255

Member
Joined
Apr 3, 2022
Messages
7
Programming Experience
Beginner
Currently working on a little project which is taking information from a SQL Server. I have a code that read’s like such:

var Item = listname.selected;
If (sqlreturndata == “1”)
{
Itemlist.selected = “item name”;
}
If (sqlreturndata == “2”)
{
Itemlist.selected = “other name”;
}
If (sqlreturndata == “3”)
{
Itemlist.selected = “another”;
}

And it goes on to 50+ numbers…

How can I make the script more efficient/clean/smaller?
 
There are a number of options. Firstly, you could use else if instead of all those distinct if statements. That would mean that, once a match was found, no more checking would be done.

Secondly, you could use a switch statement or expression. That is like using else if but the code is more succinct.

Thirdly, you could use a Dictionary, where the numbers are the keys and the names are the values.

Finally, you could just use an array of the names and index it based on the number. Arrays are zero-based, so you'd have to subtract 1 from the number to get the index.
 
Thanks, I decided to use Dictionary since it seemed like the best option for 50+ items.

I'm also trying to figure out how I can change the ID names inside the combo box into a placeholder name.
I could technically also use "if id is ####, change to name" but that doesn't seem practical. Specially since after I changed to Dictionary, it dropped my code from 600 lines to 300 and I plan on having more than 50 data values inserted into the dictionary.

C#:
string _ItemID = $"SELECT value1 FROM userDB WHERE receiveIDX='{_IDX.Text}'";
SqlCommand cmdItem = new SqlCommand(_ItemID, db.GetCon());
SqlDataReader DRTest = cmdItem.ExecuteReader();
while (DRTest.Read())
{
    comboBox1.Items.Add(DRTest.GetValue(0).ToString());
}
DRTest.Close();
Here are what my values come out as and was wondering if I could use the Dictionary function or anything else to change those IDs to have a placeholder name.

Screenshot 2022-04-03 105213.png
 
If your dictionary has both the IDs and the values, you can always looks up the key by searching for the value in the dictionary, assuming that the values are unique.
 
Not related to your question, but a serious security but waiting to happen: never inject user controlled strings directly into your SQL query.

 
Last edited:
You now seem to be asking a completely separate question. Please create a new thread for a new question and provide ALL and ONLY the information relevant to that question. You should start out by explaining exactly what you're trying to achieve.
 
Back
Top Bottom