-3

In my application I am using variables with names like dp1,dp2,....dp13 in order to use them in loops and I want to call thame in a for loop. I want to use it something like given below.

DataPoint dp1,dp2,dp3,dp4,dp5;
string s1,s2,s3,s4,s5;
for(int i=1;i<=5,i++)
{
  GetVariable("dp"+i.ToString()).Add(val1, val2);
  GetVariable("s"+i.ToString())="MyStringValue";
}

How can I do that ? I saw at some places ask me to use System.Reflection but I don't know how to use it as I want

  • 1
    you should rethink your approach. Collections are actually build to do this. What is your main aim? and why do you have so many datapoints that are solely without beeing grouped in a collection – Mong Zhu Nov 03 '21 at 14:11
  • @MongZhu I have 13 DataPoints to control 13 different charts in real time. And All the variables have indexes likes dp1,dp2,dp3.... tb1,tb2,tb3... so instead of writing the same code 13 times I want to do it in a for loop. – Mustafa Ozbalci Nov 03 '21 at 14:16
  • @Austin I checked this one and from my understanding it is more like passing value of a variable to another variable. Or did I get it wrong ? – Mustafa Ozbalci Nov 03 '21 at 14:17
  • 1
    @MustafaOzbalci So using collections doesn't help you? ... – Ergis Nov 03 '21 at 14:18
  • @Ergis I am sorry but I feel like I am not that familiar with usage of Collections usage for this case. Do you mind giving me a sample in usage? – Mustafa Ozbalci Nov 03 '21 at 14:20
  • 1
    `var dataPoints = new List(); dataPoints.Add(new DataPoint()); // whatever you're doing for dp1` Later, `foreach (var dp in dataPoints) { dp.Add(val1, val2); }`. – Heretic Monkey Nov 03 '21 at 14:23
  • Thank you @HereticMonkey I think I got how to use it – Mustafa Ozbalci Nov 03 '21 at 14:28
  • @MustafaOzbalci Can you post you GetVariable code pls? – Serge Nov 03 '21 at 14:29

2 Answers2

2

Try this:

List<DataPoint> DataPoints = new List<DataPoints>();
List<string> strings = new List<string>();

DataPoints.Add(new DataPoint);
DataPoints.Add(new DataPoint);
DataPoints.Add(new DataPoint);
DataPoints.Add(new DataPoint);
DataPoints.Add(new DataPoint);

strings.Add("");
strings.Add("");
strings.Add("");
strings.Add("");
strings.Add("");

for(int i=1;i<=5,i++)
{
     DataPoints[i].Add(val1, val2);
     strings[i] = "MyStringValue";
}
0

maybe this will work

       List<DataPoint> DataPoints = new List<DataPoint>();
        List<string> Strings = new List<string>();

    
        double val1 = 1;
        double val2 = 2;
        
        int pointNumber = 13;
        do
        {
            DataPoints.Add(new DataPoint(val1, val2));
            Strings.Add("MyStringValue");
            pointNumber--;
        }
        while (pointNumber > 0);
Serge
  • 40,935
  • 4
  • 18
  • 45