循环遍历多个标签数组

时间:2012-04-19 07:41:32

标签: c#

我通过stasckoverflows想出了如何遍历标签数组(下面的Label [] A)。我难以理解的部分是如何同时循环标签A和标签B,以便我可以使用相同的代码。请注意,我可以使用两个foreach循环,但我打算拥有相当多的标签数组(Label [] A - > Labbel [] XXX)。

Label[] A = { A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13,A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, A24, A25, A26, A27, A28, A29, A30, A31, A32, A33, A34, A35, A36, A37, A38, A39, A40, A50, A51, A52, A53, A54, A55, A56, A57, A58, A59, A60 };
            Label[] B = { B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15, B16, B17, B18, B19, B20, B21, B22, B23, B24, B25, B26, B27, B28, B29, B30, B31, B32, B33, B34, B35, B36, B37, B38, B39, B40, B50, B51, B52, B53, B54, B55, B56, B57, B58, B59, B60 };
            Graphics g = this.CreateGraphics();
            Pen pen = new Pen(Color.Blue, 1);
            g.DrawRectangle(pen, RectangleDrawer.rect_x, RectangleDrawer.rect_y, RectangleDrawer.rect_w, RectangleDrawer.rect_z);

            foreach (Label l in A)
            {
                if (l.Location.X > RectangleDrawer.rect_x && l.Location.X < (RectangleDrawer.rect_x + RectangleDrawer.rect_w) - 25 &&
                    l.Location.Y > RectangleDrawer.rect_y && l.Location.Y < (RectangleDrawer.rect_y + RectangleDrawer.rect_z) - 25)
                {
                    l.BackColor = col;
                }

非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以拥有一个数组来保存标签的所有数组,然后执行:

foreach (Label[] labels in LabelsArrays)
{
    foreach (Label l in labels)
    {
        if (l.Location.X > RectangleDrawer.rect_x &&
            l.Location.X < (RectangleDrawer.rect_x + RectangleDrawer.rect_w) - 25 &&
            l.Location.Y > RectangleDrawer.rect_y &&
            l.Location.Y < (RectangleDrawer.rect_y + RectangleDrawer.rect_z) - 25)
        {
            l.BackColor = col;
        }
    }
}

或者您可以使用LINQ扩展方法并执行此操作:

foreach (Label l in labelsA.Union(labelsB).Union(labelC))
{
    if (l.Location.X > RectangleDrawer.rect_x &&
        l.Location.X < (RectangleDrawer.rect_x + RectangleDrawer.rect_w) - 25 &&
        l.Location.Y > RectangleDrawer.rect_y &&
        l.Location.Y < (RectangleDrawer.rect_y + RectangleDrawer.rect_z) - 25)
    {
        l.BackColor = col;
    }
}