The Any()
overload with empty parameters return true if there exists something to enumerate. Furthermore its returns a boolean value, so if you concatenate that the way you have done with a string, your if condition looks like this:
if(con.Name == "textBoxTrue")
//or
if(con.Name == "textBoxFalse")
So you have to do like Oliver has shown. Another (shorter) option is:
if (numbers.Any(n => con.Name == "textBox" + n))
{
MessageBox.Show("Something");
}
The entire foreach
thing can be written in one line (this is where Linq helps):
foreach (var x in this.Controls
.OfType<TextBox>()
.Where(con => numbers.Any(n => con.Name == "textBox" + n)))
{
MessageBox.Show("Something");
}
But if what you're doing is more complex stuff, then its better to write foreach
as such for readability.
You can also take advantage of various array initialization syntaxes C# offers. Specifying the size when you're adding elements to array makes it little redundant. See this. So it need be only:
var numbers = new[] { "3", "4", "5", "6", "7" }; //may replace var with string[]
//or
string[] numbers = { "3", "4", "5", "6", "7" };
Instead of
string[] numbers = new string[5] { "3", "4", "5", "6", "7" };