如何在if语句中组合多个OR语句

时间:2016-11-15 11:50:10

标签: c#

说出来:

if (stars == 2 || stars ==6 || stars ==10)
{
    do something
}

是否有办法将它们组合在一起,就好像:

if (stars == {2, 4, 6}) <--- MATLAB style
{
       do something
}

2 个答案:

答案 0 :(得分:12)

你可以写一个像这样的扩展名:

public static class GenericExtensions
{
    public static bool In<T>(this T @this, params T[] listOfItems)
    {
        if (null == listOfItems) return false;
        return listOfItems.Contains(@this);
    }
}

然后像:

一样使用它

if (2.In(1,2,3,4))

答案 1 :(得分:4)

不是语言“MATLAB样式”的一部分,但您可以使用数组IndexOf

var items = new []{2,4,6};
if(items.IndexOf(stars) > -1)
{
  // do something
}

或类似于Contains

var items = new List<int>{2,4,6};
if(items.Contains(stars))
{
  // do something
}