简体   繁体   中英

Check if object name equals “textbox” + numberarray.Any()?

How would I be able to check the combination of textbox + numbers.Any() in one if statement such that it matches the name of the control?

foreach (Control con in this.Controls)
{
    if (con is TextBox)
    {
        if (con.Name == "textBox" + numbers.Any())
        {
            MessageBox.Show("Something");
        }
    }
}

These are the numbers:

string[] numbers = new string[5] { "3", "4", "5", "6", "7" };

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

尝试:

numbers.Select(n => string.Format("textBox{0}", n)).Contains(con.Name);

You can also use this :

var a="textBox5".Split(new string[]{"textBox"},StringSplitOptions.RemoveEmptyEntries);

if (a.Length==2) && numbers.Contains(a[1])) 
{
//  exists...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM