简体   繁体   English

检查多个变量C#的相等性是否相等

[英]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 是否有类似的内容:如果所有这些文本框的值都为!= string.Empty,则执行某些操作

You could put the textboxes in an array and use linq like that: 您可以将文本框放在一个数组中,然后使用linq:

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: 或者(如Habib所指出的),如果所有这些文本框都在一个容器控件中, 并且它们是该控件上仅有的文本框,则可以使用以下命令:

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 . OfType<>()返回在所有控件的枚举containingControl的控制集合,该集合的类型的TextBox ,你可以然后简单地通过该序列与遍历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). 请注意(如其他人所指出的那样),使用string.IsNullOrEmpty()比与string.Empty进行比较是一种更好的做法(因为已经包含了null检查,尽管在文本框中这无关紧要)。

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: 或用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.) (这具有许多优点:DRY,关注点分离等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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