我们如何使用&&编写foreach循环操作者 [英] how we write foreach loop with && operator

查看:86
本文介绍了我们如何使用&&编写foreach循环操作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我有3个foreach循环...

Hello,
I have 3 foreach loop like...

foreach (DropDownList drodown in pnlTextBoxes.Controls.OfType<dropdownlist>())
 {
  foreach (DropDownList drodown1 in pnlTextBoxes.Controls.OfType<dropdownlist>())
     {
     foreach (TextBox textBox in pnlTextBoxes.Controls.OfType<textbox>())
        {
        }
     }
}





我希望将所有动态控制转换为单个foreach循环。

我不知道怎么写你可以给我发送代码吗。



I want this all dynamic contol into single foreach loop.
I dont have idea how to write can you send me code for that.

推荐答案

我的猜测是你要做这样的事情:
My guess is that you want to do something like this:
foreach(Control cntrl in pnlTextBoxes)
{
    if(cntrl is DropDownList)
    {
       DropDownList ddl = cntrl as DropDownList;
       // handle DropDownList
    }
    else if (cntrl is TextBox)
    {
       TextBox tbx = cntrl as TextBox;
       // handle TextBox
    }
}


foreach循环只能在单个可同类型的一个维上运行。要合并列表,您需要找到公分母类型。在您的情况下,下拉列表中前两个的公分母类型,但如果您包含文本框,则公共分母类型为Control。



A foreach loop can only operate on one dimension of a single ienumerable type. To merge the lists you have you need to find a common denominator Type. In your case, the common denominator type of the first two in dropdownlist but if you include the textbox then the common denominator type is Control.

List<control> controls = new List<control>();

controls.AddRange(pnlTextBoxes.Controls.OfType<dropdownlist>())
//etc</dropdownlist></control></control>



PS:你知道你有第一个和第二个列表有相同的吗?



另一种选择是使用Linq选择列表:




PS: you are aware that the first and second lists you have there are identical?

Another option is to select into the list using Linq:

Type[] dynamicControlTypes = {typeof(DropDownList), typeof(TextBox), /*etc...*/);
foreach(Control c in pnlTextBoxes.Controls.Where(c=>dynamicControlTypes.contains(c.GetType))){

}


这篇关于我们如何使用&amp;&amp;编写foreach循环操作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆