1

I have an error code here, because I can't check if string is equal to string[].

public void SetCh1Probe(string input)
{
    string[] option= {"1:1", "1:10", "1:100"}

    //I wanna check if input is equal to any of the string array
    if (input != option.Any(x => x == option))
    {
        MessageBox.Show("Invalid Input");
    }

    else
    {
        //Proceed with other stuffs
    }
}

I will have tons of methods like this, each with different string[] options. I really want to have a neat template that I can use for the rest of the methods. Can anybody help?

3
  • 2
    I believe setting.Any should be option.Any If I understand your question correctly Commented Nov 18, 2015 at 6:04
  • 2
    Possible duplicate of Check if a value is in an array (C#) Commented Nov 18, 2015 at 6:04
  • Yea, that was a typo. Anyway, sorry for the duplicate. I can't believe I couldn't find that thread before posting. Commented Nov 18, 2015 at 6:07

2 Answers 2

5

Change your condition from

if (input != option.Any(x => x == option))

To

if (!option.Any(x => x == input))

Or another alternative

if (option.All(x => x != input))
Sign up to request clarification or add additional context in comments.

Comments

1

Please try with the below code snippet.

    public void SetCh1Probe(string input)
    {
        string[] setting = { "1:1", "1:10", "1:100" };

        //I wanna check if input is equal to any of the string array
        if (!setting.Contains(input))
        {
            //MessageBox.Show("Invalid Input");
        }

        else
        {
            //Proceed with other stuffs
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.