2016-11-08 31 views
1

我有512个独立的radio buttons,他们每个人都与一个bool显示相关。更好的循环性能来检查单选按钮

我做了一个for loop的功能,但它使用了大量的CPU。有一个更好的方法吗?

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]; 
} 
+0

可以使用foreach循环。这是一个WinForm或WPF? –

+1

我认为Controls.find使用大量的CPU。你怎么看? – tebdilikiyafet

回答

1

你可以先检索所有单选按钮,然后事后迭代在内存中是这样的:

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]; 
} 

这应该是更有效的。

+2

这假定所有单选按钮都直接包含在此容器中。如果它们分散在不同的容器中,这将不起作用 – Steve

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

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]; 
} 
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]; 
} 
+0

您可以提供更多关于为什么选择此代码的更多上下文。对@tebdilikyafet提供的代码有什么好处 –

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]; 
    }