更好的循环性能来检查radiobuttons

时间:2016-11-08 08:35:30

标签: c# for-loop radio-button

我有512个单独的radio buttons,每个bool都与要显示的for loop相关。

我使用for (int k = 0; k < NUMWORDS_FOR_PLCTOHMI_BOOLS * 16; k++) { string sRadioButtonName = "radioButton_PLCtoHMI_Bool" + k.ToString(); RadioButton r = Controls.Find(sRadioButtonName, true)[0] as RadioButton; r.Checked = KepwarearrWordtoBools_PLCtoHMI[k]; } 创建了一个函数,但它使用了大量的CPU。有更好的方法吗?

{{1}}

5 个答案:

答案 0 :(得分:1)

你可以先检索所有的radiobuttons,然后在内存中迭代它们,如下所示:

var radioButtons = this.Controls.OfType<RadioButton>();

for (int k = 0; k < NUMWORDS_FOR_PLCTOHMI_BOOLS * 16; k++)
{
    string sRadioButtonName = "radioButton_PLCtoHMI_Bool" + k.ToString();
    RadioButton r = radioButtons.Single(x => x.Name == sRadioButtonName);
    r.Checked = KepwarearrWordtoBools_PLCtoHMI[k];
}

这应该更有效率。

答案 1 :(得分:1)

如果控件位于列表中,如何执行此操作的示例:

List<RadioButton> radioButtons = new List<RadioButton>(); 
//Fill the List with the controls

for (int k = 0; k < radioButtons.Count; k++)
{
   radioButtons[k].Checked = KepwarearrWordtoBools_PLCtoHMI[k];
}

唯一剩下的就是填补List

答案 2 :(得分:0)

我的建议是创建一个词典,因为查找项目的访问时间非常快。

创建按钮时:

private Dictionary<String, RadioButton> buttons = new Dictionary<String, RadioButton>();

//Wherever you create those buttons
buttons.Add("radiobutton_PLCtoHMI_Bool" + k.toString());

//When you want to get them
for (int k = 0; k < NUMWORDS_FOR_PLCTOHMI_BOOLS * 16; k++)
{
    string sRadioButtonName = "radioButton_PLCtoHMI_Bool" + k.ToString();
    //You find it faster than with Controls.Find()
    RadioButton r = buttons(sRadioButtonName);
    r.Checked = KepwarearrWordtoBools_PLCtoHMI[k];
}

答案 3 :(得分:0)

foreach (var rb in this.Controls.OfType<RadioButton>())
{
   var k = rb.Name.Substring(25); // because "radioButton_PLCtoHMI_Bool" has 25 characters
   int i;
   if(int.TryParse(k, out i)) //if k is an integer 
      rb.Checked = KepwarearrWordtoBools_PLCtoHMI[i];
}

答案 4 :(得分:0)

我建议逻辑反转:循环RadioButton我们检测是否应该检查每个ReadioButton

  // providing that all the radio buttons are on the form;
  // if they are on, say, myPanel, put myPanel instead of "this"
  var rButtons = this
    .Controls
    .OfType<RadioButton>()
    .Where(item => item.Name.StartsWith("radioButton_PLCtoHMI_Bool"));

  foreach (var rb in rButtons) {
    int index;

    if (int.TryParse(rb.Name.SubString("radioButton_PLCtoHMI_Bool".Length), out index))
      if (index >= 0 && index < KepwarearrWordtoBools_PLCtoHMI.Length)
        rb.Checked = KepwarearrWordtoBools_PLCtoHMI[index];
  }