简体   繁体   中英

More Efficient OR Statement

I currently have C# code checking for user input as such:

if (e.KeyCode == Keys.Enter && InputTextbox.Text.Contains("good morning")
   ||
    e.KeyCode == Keys.Enter && InputTextbox.Text.Contains("morning"))

Is there another way to use the || "or" statement so that it can all be in the one line? Something like:

if (e.KeyCode == Keys.Enter && InputTextbox.Text.Contains("good morning" || "morning")
var allowedText = new List<string> { "good morning", "morning" };

if (e.KeyCode == Keys.Enter && allowedText.Contains(InputTextbox.Text))
{
    // do something
}

You can create an array with the values you want to check and then check if the array contains the TextBox value

string[] a = {"good morning" , "morning");

if (e.KeyCode == Keys.Enter && a.Contains(InputTextbox.Text))
{
}

Hm, for instance: if your InputTextBox is: "Hello good morning" I don't think the above answers will work, if this is what you seek (having a posibly larger string checked against the given smaller strings), you have to check it the other way around:

if (e.KeyCode == Keys.Enter && (InputTextbox.Text.Contains("good morning") || InputTextbox.Text.Contains("morning"))

Just thought I'd point it out, if not the case ignore this answer.

This is sufficient:

if (e.KeyCode == Keys.Enter && InputTextbox.Text.Contains("morning"))
{
}

It is because if InputTextbox.Text.Contains("good morning") is true , InputTextbox.Text.Contains("morning") must be true as well.

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