简体   繁体   English

if语句的多个值

[英]Multiple value for if-statement

If my statement contains two conditions: 如果我的陈述包含两个条件:

string searchx = "some string"; 

if ((searchx.Contains("a1")) || (searchx.Contains("a2")))
{
...
}

But how to get list of values with single variable for statement? 但是如何用语句的单个变量获取值列表?

If I got a1, a2, a3, a4, a5, a6, a7, a8, a9... 如果我得到a1, a2, a3, a4, a5, a6, a7, a8, a9...

Can I do it somehow this way, seems it is wrong attempt: 我能用这种方式做到这一点,似乎是错误的尝试:

var valueList = new List<string> { "a1", "a2", "a3", "a4"};

But just to explain what I want to do, so if any value exist under valueList , condition is accepted: 但只是为了解释我想要做什么,所以如果valueList下存在任何值,则接受条件:

if (searchx.Contains(valueList)) 
{
...
}

The best if I can get multiple value return I guess or any other way to get statement with updated list of values through single variable of any other way, which can work for me this way? 最好的,如果我可以得到多个值返回我猜或任何其他方式通过任何其他方式的单个变量获得更新的值列表,这可以这样对我有用吗?

This has worked for me: 这对我有用:

if (valueList.Any(x => searchx.Contains(x)))
{
}

or even shorter (thanks to rajeeshmenoth) 甚至更短(感谢rajeeshmenoth)

    if(valueList.Any(searchx.Contains))

You can try and use Except 您可以尝试使用Except

if (valueList.Except(searchx).Any())
{

}

Not the best solution, but works. 不是最好的解决方案,但有效。

bool containsValue(string search)
{
var valueList = new List<string> { "a1", "a2", "a3", "a4"};
foreach (string s in valueList)
 {
 if(search.Contains(s))
  return true;
 }
return false;
}

and use it like : 并使用它像:

if (containsValue(searchx))
{
... do something ...
}

You can use the Linq : 你可以使用Linq:

  bool b = valueList.Any(searchx.Contains);

Try this : 尝试这个 :

    string searchx = "a8"; 
    var valueList = new List<string>{"a1", "a2", "a3", "a4"};

    if (valueList.Any(searchx.Contains))
        Console.WriteLine("Data Matching..!!");
    else
        Console.WriteLine("Not Matching..!!");

Demo : Click here 演示: 点击这里

You can make a foreach loop 你可以做一个foreach循环

string search = "GIVE A STRING";
List<string> DataList = new List<string> {"a1", "a2", "a3",.....};
foreach(string Data in DataList)
{ 
  if(search.Contains(Data))
  { //TODO }
}

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

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