检查变量是否在特定值列表中

本文关键字:列表 变量 是否 检查 | 更新日期: 2023-09-27 18:16:33

有没有一种更短的方法来写这样的东西:

if(x==1 || x==2 || x==3) // do something

我要找的是这样的东西:

if(x.in((1,2,3)) // do something

检查变量是否在特定值列表中

您可以通过使用List来实现这一点。包含方法:

if(new []{1, 2, 3}.Contains(x))
{
    //x is either 1 or 2 or 3
}
public static bool In<T>(this T x, params T[] set)
{
    return set.Contains(x);
}
...
if (x.In(1, 2, 3)) 
{ ... }

必读:MSDN扩展方法

如果它在IEnumerable<T>中,请使用以下命令:

if (enumerable.Any(n => n == value)) //whatever

另外,这里有一个简短的扩展方法:

public static bool In<T>(this T value, params T[] input)
{
    return input.Any(n => object.Equals(n, value));
} 

把它放在static class中,你可以这样使用它:

if (x.In(1,2,3)) //whatever
int x = 1;
if((new List<int> {1, 2, 3}).Contains(x))
{
}

从C#9开始,该语言支持一种模式:

if(x==1 || x==2 || x==3) foo();

可以写成:

if (x is (1 or 2 or 3)) foo();

这些模式可能相当复杂。我在这里找到了这个案例的描述:https://learn.microsoft.com/en-US/dotnet/csharp/language-reference/operators/patterns#precedence-和检查的顺序

我完全在猜测,如果我错了,请更正代码:

(new int[]{1,2,3}).IndexOf(x)>-1

您可以创建一个简单的Dictionary<TKey, TValue>,用作该问题的决策表:

        //Create your decision-table Dictionary
        Action actionToPerform1 = () => Console.WriteLine("The number is okay");
        Action actionToPerform2 = () => Console.WriteLine("The number is not okay");
        var decisionTable = new Dictionary<int, Action>
            {
                {1, actionToPerform1},
                {2, actionToPerform1},
                {3, actionToPerform1},
                {4, actionToPerform2},
                {5, actionToPerform2},
                {6, actionToPerform2}
            };
        //According to the given number, the right *Action* will be called.
        int theNumberToTest = 3;
        decisionTable[theNumberToTest](); //actionToPerform1 will be called in that case.

一旦初始化了Dictionary,剩下的就是:

decisionTable[theNumberToTest]();

这个答案指的是C#的一个可能的未来版本;-(如果您考虑切换到Visual Basic,或者如果Microsoft最终决定在C#中引入Select-Case语句,它会是这样的:

Select Case X
    Case 1, 2, 3
    ...
End Select