Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple variables to a list

Tags:

variables

c#

I wonder if there is any way to write the following code a lot shorter...

public PictureBox pb1; 
public PictureBox pb2; 
public PictureBox pb3;
..... 
public PictureBox pb50;

And then, is there any way to add all those variables to a list, without having to perform the same ugly code again.

listPB.add(pb1); listPB.add(pb2);...... ListPB.add(pb50);

The method I use is really dumb and I hoped that there were some other way to do it. Thanks for the help!

like image 305
Easterlily Avatar asked Apr 17 '14 07:04

Easterlily


People also ask

Can you put variables in a list?

Since a list can contain any Python variables, it can even contain other lists.

Is it possible to assign multiple VAR to values in list?

We generally come through the task of getting certain index values and assigning variables out of them. The general approach we follow is to extract each list element by its index and then assign it to variables. This approach requires more line of code.


1 Answers

You can make an ad-hoc collection like this:

PictureBox[] pictureBoxen = {pb1, pb2, pb3, ..., pb50};

and then you can use AddRange on the list to add them

listPB.AddRange(pictureBoxen);

Or if listPB is created on that place, and only contains those variables, you could do:

List<PictureBox> listPB = new List<PictureBox>{pb1, pb2, ..., pb50};

Note that this kind of syntax was only introduced in C#3, in 2008, so it is safe to assume that you are using that or higher.

For C#2 and below, looping is the best I could come up with.

like image 57
SWeko Avatar answered Sep 22 '22 23:09

SWeko