I would use a pair of arrays or dictionaries (setting them up is left as the proverbial exercise for the reader):
labels[index].Text = "Device " + (index + 1) + " has temperature "
+ temperatures[index].ToString(formatString) + " ℃";
EDIT
From the code in your comment, it seems you want to identify a label by name, and that you will derive the name from an integer variable, like this:
for (int i=1; i<=6; i++)
{
Label label = GetLabelForIndex(i);
//do something with the label here
}
So the question is, how will you get the label for a given index? In other words, what is the implementation of GetLabelForIndex(int)
? The answer to that question depends on what kind of Label
we're talking about. What library does it come from? Is it WinForms? Silverlight? WPF? If it's WinForms, see Get a Windows Forms control by name in C#. If WPF or Silverlight, see Find WPF control by Name. The accepted answer here also proposes using a dictionary with a string key, which is similar to my suggestion above.
Unless you're doing this thousands of times a second, the performance benefit of using a dictionary is probably insignificant, in which case you should just use Find
or FindName
directly.