Tacit
Tacit

Reputation: 908

Populating a nested List

I want to add my buttons in this list

List<List<Button>> buttonss = new List<List<Button>>();

This is how i create my buttons:

Button[][] buttons;

In the method(also try to populate the list but it is not right):

for (int r = 0; r < row; r++)
    {
       for ( int c = 0; c < col; c++)
           {
             buttons[r][c] = new Button();
             buttonss.Add(buttons[r][c]);
           }
    }

How can i populate this list using this button array (my array has to be Button[][] and not Button[,] as it will make my life easier when I do other stuff like xml serialization

Upvotes: 0

Views: 130

Answers (2)

D Stanley
D Stanley

Reputation: 152556

I'm not sure why you're trying to store this two separate ways, but if you really need to then you need to initialize each inner array and list:

buttons = new Button[row][];
for (int r = 0; r < row; r++)
{ 
   buttons[r] = new Button[col];
   List<Button> rowList = new List<Button>();
   buttonss.Add(rowList);    
   for (int c = 0; c < col; c++)
   {
     buttons[r][c] = new Button();
     rowList.Add(buttons[r][c]);
   }
}

Another way to do it would just be to store in a jagged array and convert to a list (or vice-versa):

// From List<List> to Jagged Array
buttons = buttonss.Select(b=>b.ToArray()).ToArray();

// From Jagged Array to List<List>
buttonss = buttons.Select(b=>b.ToList()).ToList();

Upvotes: 1

cuongle
cuongle

Reputation: 75306

You can use LINQ Select:

buttonss = buttons.Select(b => b.ToList()).ToList();

Upvotes: 1

Related Questions