Reputation: 668
Can I make a dynamics switch statement, i.e if I have a list containing 1,2,3,4,5 rather than manually doing case 1:, case 2: etc can I do it using a for loop as shown below?
The code doesn't work. Visual Studio gives an error saying case has to be a referenced label, I am a beginner.
switch (selectedShow)
{
//Show list is a list of type Shows
for (int i = 0; i < showList.Count; i+=1)
{
case i:
{
waitingList[waitingList.Count].Show = showList[selectedShow];
break;
}
}
}
Upvotes: 1
Views: 5740
Reputation: 668
Using a forloop and if statement should work. I can iterate through the list using the for each loop and if the selected show (user selects in terminal) is the current iterated show. Then I can reference the show in the waitingList.
selectedShow = int.Parse(Console.ReadLine());
//Show list is a list of type Shows
for (int i = 0; i <=showList.Count;)
{
if (selectedShow == i)
{
//Count starts from 1 not 0
waitingList[waitingList.Count-1].Show = showList[selectedShow];
break;
}
}
Upvotes: 0
Reputation: 95355
It kinda seems you just want:
waitingList[waitingList.Count].Show = showList[selectedShow];
Upvotes: 2
Reputation: 4423
switch (selectedShow)
{
//Show list is a list of type Shows
for (int i = 0; i < showList.Count; i+=1)
{
waitingList[waitingList.Count].Show = showList[i];
//Add some condition if you want to break the loop.
if(breakCondition)
break;
}
}
Upvotes: 0
Reputation: 488
Switch statement is used for making a different operations for different values. thats why the "case" select the value to proceed. In your example only one operation is implemented for any value in your list. So, you don't need to apply "if" statement to check the condition where selectedShow is equal to some item in your list. Preferred way to iterate over list in C# is foreach operation. For example:
foreach (var i in showList)
{
if(i == selectedShow)
{
waitingList.Last().Show = i;
break;
}
}
I also replaced unsafe waitingList.[waitingList.Count] for more clear waitingList.Last() method (you may need to add using System.Linq; at the top of your file)
Upvotes: 1
Reputation: 48287
This code segment here:
//Show list is a list of type Shows
for (int i = 0; i < showList.Count; i+=1)
{
case i:
{
waitingList[waitingList.Count].Show = showList[i];
break;
}
}
makes no sense, for every value of i you will execute the case condition:
instead do:
for (int i = 0; i < showList.Count; i+=1)
{
waitingList[waitingList.Count].Show = showList[i];
}
Upvotes: 0
Reputation: 23078
As already specified, you do not need a case statement. You can write a code similar to the following:
//Show list is a list of type Shows
for (int i = 0; i < showList.Count; i+=1)
{
waitingList[waitingList.Count].Show = showList[i];
if (someBreakConditionFunction())
break;
}
Upvotes: 0