简体   繁体   中英

Checking for equality to the same value for more than one variable C#

Is there a shorthand version of this comparison statement:

if (txtId.Text != string.Empty && txtName.Text != string.Empty && txtBOD.Text != string.Empty && txtPhone.Text != string.Empty)
{//do something }

Is there something like: if all these textboxs values != string.Empty, then do something

You could put the textboxes in an array and use linq like that:

TextBox[] boxes = new [] {txtId, txtName, txtBOD, txtPhone};
if (boxes.All(b => !string.IsNullOrEmpty(b.Text)))
    // do something

You should store the array in a member variable of your window so you don't have to create it again for every check.


Or (as Habib pointed out) if all those textboxes are in one container control and they are the only textboxes on that control you could use this:

if (containingControl.Controls.OfType<TextBox>().All(b => !string.IsNullOrEmpty(b.Text)))
    // do something

OfType<>() returns a enumeration of all controls in the containingControl 's control collection that are of type TextBox and you can then simply iterate through this sequence with All .


Note (as others pointed out) that it's a better practice to use string.IsNullOrEmpty() than comparing against string.Empty (since a null check is already included, though that should not matter at a textbox).

You could create a method like this:

private bool AreAllEmpty(params TextBox[] toCheck)
{
    foreach (var tb in toCheck)
    {
        if (!string.IsNullOrEmpty(tb.Text)) return false;
    }

    return true;
}

Or this way with LINQ:

private bool AreAllEmpty(params TextBox[] toCheck)
{
    return toCheck.All(tb => string.IsNullOrEmpty(tb.Text));
}

And then just pass it your collection of text boxes, eg like this:

if(AreAllEmpty(textBox1, textBox2, textBox3, textBox4))
{
    // do something../
}

This approach is good if you're like me and like to reduce method size by off-loading separate operations into their own methods. (This has many advantages: DRY, separation of concerns, etc.)

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