Reputation: 2413
First off I'm sure that I am using the wrong terminology here but I will fix it if someone comments on it. Please be gentle.
So I have multiple charts
on a page and I am performing virtually identical actions on each. For demonstrative purposes lets call my charts
something like: chart1
, chart2
, ..., chartn
where n is somewhere in the vicinity of 20. What I would like to do is drop this in a for
loop and perform all the work in one smaller chunk of code, especially if I have to tweak it later.
So my question is whether or not I can vary the n part representing the object (terminology?) so I can get this done more efficiently.
i.e.:
for(int i = 0; i < 20; i++)
{
String chartName = "chart" + i;
chartName.Series.Clear();
}
I have a feeling you can't do this with a string so I was looking into doing a foreach
but I don't know how to do this with charts.
Thanks a lot!
Upvotes: 1
Views: 96
Reputation: 50336
You should put the charts in a list. For example, this makes a list of Chart
objects (or whatever your chart type is):
List<Chart> charts = new List<Chart>();
Then you can add charts:
charts.Add(new Chart());
And use them:
for (int i = 0; i < charts.Count; i++)
{
charts[i].Series.Clear();
}
Of course, you can make the charts
variable a field in your class.
You can directly initialize a list (or array, or dictionary1) like this:
List<Chart> charts = new List<Charts>()
{
new Chart(),
new Chart(),
existingChart1,
existingChart2
};
Or, if you create a new array of objects using that syntax...
Chart[] arrayOfCharts = new []
{
new Chart(),
new Chart(),
existingChart1,
existingChart2
};
...then you can add multiple objects at once using AddRange
:
charts.AddRange(arrayOfCharts);
1) You can use this so-called collection initializer syntax on any object that has a public Add
method.
Upvotes: 4
Reputation: 2089
Can you access your chart from a list/array/collection of charts like this?
for (int i = 0; i <= 19; i++) {
String chartName = "chart" + i;
Charts(chartName).Series.Clear();
}
or maybe
for (int i = 0; i <= 19; i++) {
String chartName = "chart" + i;
Charts(i).Series.Clear();
}
Upvotes: 0