0

I have few variables named as am_2,am_1,am_3 and so on. I have to find the count by typing: am_2.Count(), am_1.Count() and so on. I want to do the same in a loop. Right now I will have to write all of them separately like:

am_2.Count(),am_1.Count(),am_3.Count().... 

Is there a way that I can get the Count by not typing the variable name again and again and can do it in a loop. I tried the following code, but it did not work:

for(i=1;i<=12;i++)
{
string sm="am_"+1;

if(sm.Count()==1)
{
 Do the task.....
 }

  }

But the above code does not work. Any suggestions?

1
  • It's overall saying about problems with code design. You should probably think about re-arranging your code so that you don't face such issues. Otherwise it's gonna get worse. Commented Mar 6, 2016 at 19:22

2 Answers 2

2

You can't (easily) reference a variable by string name - nor do you usually want to. In programming, we generally deal with 3 types of numbers - 0, 1 and many. When you have many, a collection of some sort is usually a good idea.

The easiest way to do something like this would be to place all your variables in an array, and then loop over the collection. Depending on where these variables came from, it'd be nice(r) to start with a collection, but without that context - here's how you'd make a collection out of them:

var amArray = new[] { 
   am1, am2, am3, am4, am5, am6, am7, am8, am9, am10, am11, am12 
};
foreach (var am in amArray) {
   if (am.Count() > 1) {
      // do the task
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could add those variables to a list

List<String[]> am_list = new List<String[]>();
am_list.add(am_2);
am_list.add(am_1);
am_list.add(am_3);

Then loop through the list

foreach(String[] item in am_list) {
 int count = item.Count;
 //your task here
}

Remember to replace String[] with your variable type.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.