A for loop is better than switches and ifs when there are many different cases, all being a number in order. There are many reasons why but the best is: which is easier to read and write? 100 lines of cases or a few lines if a for loop?
In this scenario if you can change it to be in this form, it will be much better. We cannot move it straight over how you wanted, though, because indexing ([i]
) doesn’t work how you seem to think it does. Indexing grabs the value at the specified index of the collection, maybe an array, a list, etc..
If we change our lbl_Location1
, … to an array:
string[] lbl_Location = new string[]{ "a value 1", "a value 2", "and more" };
Obviously change the strings to the value and type of your choice. You can then do what you want and iterate through the indexes, which is better. Note that indexes start at 0
! The first value is 0
, second 1
, etc..
Implementation (notice I changed your condition in the for statement to the length of the array, this is a cleaner and simpler way to do it. Unless you were doing something different where that wasn’t just the length of the array, just stop using that and use this):
for(int i = 0; i<lbl_Location.Length; i++)
{
lbl_Location[i].Text = lblDeviceName_Selected(device_id);
}
If you don’t understand something or I misunderstood please comment!
More information on indexing:
So let’s say I have a variable called MyString1
. What you were trying to do with MyString[1]
(I have replaced i
with a 1 to further simplify this) is “look for a (for simplicity’s sake) array called MyString
and look at the second (remember, indexes start at zero!) position.” What you wanted it to do was just add a 1
at the end. When we make it an array, we are essentially making one variable that is a container for many values.
6
solved why in this case, I can use for instead of switch-case [closed]