C# 如何从foreach循环中排除特定类型的控件?
我试图验证一个表单控件,看看它们是否为空,并在我的挥舞中找到一个有趣的点C# 如何从foreach循环中排除特定类型的控件?,c#,C#,我试图验证一个表单控件,看看它们是否为空,并在我的挥舞中找到一个有趣的点 List<string> emptycontrols = new List<string>(); foreach (Control control in Mainform.V_Datafield.Controls) { if (control.Text.Contains(null)) { emptycontrols.Add(control.Name); }
List<string> emptycontrols = new List<string>();
foreach (Control control in Mainform.V_Datafield.Controls)
{
if (control.Text.Contains(null))
{
emptycontrols.Add(control.Name);
}
}
if (emptycontrols.Count > 0)
{
MessageBox.Show("Empty fields detected:", emptycontrols.ToString());
}
List emptycontrols=new List();
foreach(Mainform.V_Datafield.Controls中的控件)
{
if(control.Text.Contains(null))
{
emptycontrols.Add(control.Name);
}
}
如果(EmptyControl.Count>0)
{
Show(“检测到空字段:”,emptyControl.ToString());
}
上面是我的普通解决方案,当运行时,出现一个控件,即DateTimePicker
控件永远不能为空,这是非常正确的
最后,我的问题是如何将DateTimePicker
控件从foreach
循环中排除,以便它忽略它,但继续检查其他控件
groupbox(V_数据字段
)包含:
- 10个文本框
- 1个RichTextBox
- 1个如上所述的DateTimePicker
foreach
循环中,您可以随时检查以下内容
if (control is DateTimePicker)
continue;
您可以这样使用
is
:
foreach (Control control in Mainform.V_Datafield.Controls)
if (!(control is DateTimePicker) && string.IsNullOrEmpty(control.Text))
emptycontrols.Add(control.Name);
或者,实际上,可以使用LINQ删除循环,使其成为:
var emptyControls = Mainform.V_Datafield.Controls
.Cast<Control>()
.Where(control => !(control is DateTimePicker))
.Where(control => string.IsNullOrEmpty(control.Text))
.Select(control => control.Name);
var emptyControls=Mainform.V_Datafield.Controls
.Cast()
.Where(控件=>!(控件为日期时间选择器))
.Where(control=>string.IsNullOrEmpty(control.Text))
.Select(control=>control.Name);
使用两个
,其中
保留前一个代码的逻辑,但是可以使用和&
合并它们控件.Text.Contains(null)
看起来很奇怪。您可能想编写string.IsNullOrEmpty(control.Text)
。除此之外,循环使用Mainform.V_Datafield.Controls.Where(c=>!(c是DateTimePicker))
你知道,现在我已经看到了这一点,这看起来确实更有意义,让我们来改变一下真正的快速方式吧。我更喜欢LINQ解决方案(使用Where)通过循环内部的类型检查。@Clemens无论如何,我可以切换接受的答案,如果这更有意义,我可以问一下为什么LINQ解决方案更可取吗?另一个答案也说明了如何避免整个循环。在LINQ语句末尾添加.ToList()
将执行该语句,并使其返回您原来拥有的列表。不确定是否为空Text==null
可能也合适。刚才使用的IsNullOrEmpty
因为OP似乎喜欢你在问题注释中的命题请原谅我的沉默,但是:'Control.ControlCollection'不包含“Where”的定义,也不包含扩展方法'Where'接受类型的第一个参数“Control.ControlCollection”
@JMC对不起!我假设它实现了IEnumerable
,我会修正我的答案。@Halex一点问题都没有!我很感激你的快速反应(你也能容忍我)现在工作得很好:D