2015-11-18 30 views
1

我在這裏有一個錯誤代碼,因爲我無法檢查字符串是否等於string []。C#Linq - 如果輸入不等於任何字符串[]

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

我會有很多這樣的方法,每個都有不同的string[] options。我真的想要一個整潔的模板,我可以使用其餘的方法。任何人都可以幫忙嗎?

+2

我相信'setting.Any'應該是'option.Any'如果我明白你的問題的正確 –

+2

可能的複製[檢查是否值是一個數組(C#)](HTTP://計算器。 com/questions/13257458/check-if-a-value-is-an-an-array-c) –

+0

是的,那是一個錯字。無論如何,抱歉的重複。我無法相信在發佈之前我找不到該線索。 –

回答

4

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

改變你的條件要

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

或者另一種選擇

if (option.All(x => x != input)) 
1

請與下面的代碼片段嘗試。

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