2013-03-04 212 views
1

我正在寻找一个按钮的二维数组。我已经命名了b1,b2,b3,b4(b5将在下一行等)。 我可以添加的按钮一维列表,如下图所示:如何将按钮列表转换为数组?

List<Button> buttonList; 

buttonList = new List<Button> {b1,b2,b3,b4,b5 (etc.)}; 

现在,我需要把这些按钮到一个数组,它是一种像这样:

{{0, 1, 2 , 3}, {4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}}; 

哪里b1将为0,b2将等于1等等。

我对此很陌生,无法找到任何相似的东西,我对于/ foreach循环不太好,也许其中一个需要这样做,所以我该怎么做?

+6

*我不与/ foreach循环*太好了 - 所以你为什么不先尝试更多地了解他们,而不是希望我们做你的工作? – balexandre 2013-03-04 06:59:06

回答

0

尝试somethinhg这样的:

var lst = new List<List<Button>>(); 
lst.Add(new List<Button>{b1,b2,b3}); 
lst.Add(new List<Button>{b4,b5,b6}); 

foreach(var buttonList in lst) 
{ 
    foreach(var button in buttonList) 
    { 
    //do stuff with button 
    } 
} 

或者,如果你需要的保藏是数组(thatever原因)

var ary = List<Button>[2]; //two elements in ary. 
ary[0] = new List<Button>{b1,b2,b3}; 
ary[1] = new List<Button>{b4,b5,b6}; 

循环保持不变。

1
var myArray = new Button[,] { { b1, b2, b3, b4 }, 
           { b5, b6, b7, b8 }, 
           { b9, b10, b11, b12 }, 
           { b13, b14, b15, b16 } }; 
0

您可以使用此代码

var x = new List<List<Button>> 
        { 
         new List<Button> 
          { 

          b4,b5,b6 

          } 
        }; 

 var x= new Button[] { { b1, b2, b3, b4 } }; 
0

我建议使用列表而不是数组列表使用。

var groupedList = new List<List<Button>>(); 

for(i = 0; i < buttonList.length/4 + 1; i++) //plus one will ensure we don't loose buttons if their number doesn't divide on four 
{ 
    groupedList.Add(buttonList.Skip(i * 4).Take(4)); 
} 
0

试试这个,如果你需要你的List<Button>int [][]

var nums = new[] { new[] { 0, 1, 2, 3 }, new[] { 4, 5, 6, 7 }, new[] { 8, 9, 10, 11 }, new[] { 12, 13, 14, 15 } }; 
int counter = 0; 
foreach (int[] ints in nums) 
{ 
    foreach (int i in ints) 
    { 
     buttonList[counter].Text = i.ToString(); 
     counter++; 
    } 
} 

一种更好的方式来处理,以更新这可以是:

private List<Button> buttonList = new List<Button>(); 
private void addButtonsDynamically(object sender, EventArgs e) 
{ 
    int top = 10, left = 10; 
    for (int i = 1; i <= 16; i++) 
    { 
     Button btn = new Button(); 
     btn.Parent = this; 
     btn.Size = new Size(25, 25); 
     btn.Text = (i - 1).ToString(); 
     btn.Location = new Point(left, top); 

     left += 35; 
     if (i > 0 && i % 4 == 0) 
     { 
      top += 35; 
      left = 10; 
     } 
    } 
} 

它会创建这样一个输出:

sample output

0

如果你想你的列表转换(连续4)数组这里是一个LINQ的方式来做到这一点:

var buttonsArray = buttonsList 
        .Select((b, i) => new {Index = i, Button = b}) 
        .GroupBy(x => x.Index/4) 
        .Select(x=>x.Select(y=>y.Button).ToArray()) 
        .ToArray();