1

I have 4 string List variables:

var cat1 = new List<string>();
var cat2 = new List<string>();
var cat3 = new List<string>();
var cat4 = new List<string>();

if (value== "1")
{
    cat1.Add(value.ToString());
}

else if (value== "2")
{
    cat2.Add(value.ToString());
}

else if (value == "3")
{
    cat3.Add(value.ToString());
}

else if (value== "4")
{
    cat4.Add(value.ToString());
}

Instead of using 4 if-else, can I use for-loop by changing variable names in each loop increment?

Such as:

for (int i = 1; i < 5; i++)
{
    cat[i].Add(value.ToString());
}
1
  • 1
    wait, do you want to add value.ToStrong() to all of your lists? Why don't you just add it then to one-by-one? Commented May 22, 2019 at 2:46

1 Answer 1

4

Place your lists in array and use indexes from 0 to 4 in for loop:

var cat1 = new List<string>();
var cat2 = new List<string>();
var cat3 = new List<string>();
var cat4 = new List<string>();

var cat = new[] { cat1, cat2, cat3, cat4 };

for (int i = 0; i < 4; i++)
{
    cat[i].Add(value.ToString());
}
Sign up to request clarification or add additional context in comments.

2 Comments

your code will add value.ToString() to all of this lists. Why don't you just var v = value.ToString(); cat1.Add(v); cat2.Add(v); cat3.Add(v); cat4.Add(v);?
@vasily.sib thank you for your advice. I have implemented it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.