andrew slaughter
andrew slaughter

Reputation: 1117

Select a c# List dynamically

I have the following code:

var op1 = new List<KeyValuePair<string, string>>();
op1.Add(new KeyValuePair<string, string>("8-9-10-11-12-13", "All"));

just an example, but I have 3 of these op1, op2 and op3. I then have a loop to loop through the values in one of them. I want to loop through one of them based on a selection made elsewhere so i have:

foreach (KeyValuePair<string, string> kvp in op1)
{

But I want to alter op1 dynamically. Can anyone advise me?

thanks

Upvotes: 0

Views: 94

Answers (2)

Karthik T
Karthik T

Reputation: 31952

var opx = false ? op1 : true ? op2: op3;  // the condition logic here is just to show, do not do this :P 

//later
foreach (KeyValuePair<string, string> kvp in opx)

Assign your choice to a variable, here opx and loop on opx which will loop on your choice

Upvotes: 1

dannykay1710
dannykay1710

Reputation: 2013

I'm assuming the aim here is to not repeat the foreach statement multiple times inside an if statement or similar?

You must have some logic to determine which list you want to loop through? I would create a fourth list (let's just call this op) and use op in your foreach statement. Then above the foreach, determine which one you want to loop through and assign it to the op variable. This way you reduce any code duplication but still allow the loop selected to be looped through

Upvotes: 0

Related Questions