【问题标题】:C# Linq - If input is not equal to any of the string[]C# Linq - 如果输入不等于任何字符串 []
【发布时间】:2015-11-18 06:01:37
【问题描述】:

我这里有一个错误代码,因为我无法检查 string 是否等于 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
    }
}

我会有很多这样的方法,每个方法都有不同的string[] options。我真的很想有一个可以用于其余方法的简洁模板。有人可以帮忙吗?

【问题讨论】:

  • 我相信 setting.Any 应该是 option.Any 如果我理解你的问题
  • 是的,这是一个错字。无论如何,对不起重复。我不敢相信在发布之前我找不到该主题。

标签: c# arrays string linq if-statement


【解决方案1】:

改变你的条件

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

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

或者其他选择

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

【讨论】:

    【解决方案2】:

    请尝试以下代码 sn-p。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-22
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多