我如何才能在一个 if 语句中检查 textbox + numbers.Any()
的组合,使其与控件的名称相匹配?
foreach (Control con in this.Controls)
{
if (con is TextBox)
{
if (con.Name == "textBox" + numbers.Any())
{
MessageBox.Show("Something");
}
}
}
这些是数字:
string[] numbers = new string[5] { "3", "4", "5", "6", "7" };
最佳答案
具有空参数的 Any()
重载如果存在要枚举的内容则返回 true。此外,它返回一个 bool 值,因此如果您按照处理字符串的方式连接该值,则您的 if 条件如下所示:
if(con.Name == "textBoxTrue")
//or
if(con.Name == "textBoxFalse")
所以你必须像 Oliver 展示的那样去做。 另一个(更短的)选项是:
if (numbers.Any(n => con.Name == "textBox" + n))
{
MessageBox.Show("Something");
}
整个 foreach
可以写在一行中(这是 Linq 的帮助):
foreach (var x in this.Controls
.OfType<TextBox>()
.Where(con => numbers.Any(n => con.Name == "textBox" + n)))
{
MessageBox.Show("Something");
}
但是,如果您正在做的是更复杂的事情,那么为了可读性,最好这样编写 foreach
。
您还可以利用 C# 提供的各种数组初始化语法。在向数组添加元素时指定大小会使它变得有点多余。 See this .所以它只需要:
var numbers = new[] { "3", "4", "5", "6", "7" }; //may replace var with string[]
//or
string[] numbers = { "3", "4", "5", "6", "7" };
代替
string[] numbers = new string[5] { "3", "4", "5", "6", "7" };
关于c# - 检查对象名称是否等于 "textbox"+ numberarray.Any()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18809871/