0

I am trying to use a for loop to iterate through a series of variable names each ending in a number from 1 to 10. I have seen a few other answers to this question but have been unable to make any work for my specific situation. My code is as follows:

        string cat2Pos0 = cat2[0];
        int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count();
        List<int> indexOfPos0 = new List<int>();
        bool check = cat2.Contains(cat2Pos0);
        int index = 0;
        if (check == true)
        {
            for (int i = 0; i < numOfPos0; i++)
            {
                index = cat2.FindIndex(x => x == cat2Pos0);
                indexOfPos0.Add(cat2.IndexOf(cat2Pos0));
            }
        }
        else if (cat2Pos0 == "-")
        {
            numOfPos0 = 17;
        }

I need to loop through 10 variables names cat1 - cat10. In the code: whenever there is the phrase "cat" I need to be able to adjust it depending on a for loop e.g. cat1 or cat5:

string cat3pos0 = cat3[0];

or:

index = cat3.FindIndex(x => x == cat3Pos0);

Unfortuantely, I am unable to simply write out each variation individually as that would use up almost 3700 lines of code and I was hoping that there would be a better way of achieveing this.

Many thanks, all help is greatly appreciated,

Josh

Josh
  • 11

1 Answers1

1

See here how to use reflection for this. (something like this.GetType().GetField("cat" + i.ToString());.)

But I would really suggest changing your variables to one array of 10 variables. So cat will be an array of arrays (since your cat's seem to be arrays).

ispiro
  • 26,556
  • 38
  • 136
  • 291