有没有更简短的方式来表达这个意思:
if(x==1 || x==2 || x==3) // do something
我所需要的是类似于这样的东西:
if(x.in((1,2,3)) // do something
if(new []{1, 2, 3}.Contains(x))
{
//x is either 1 or 2 or 3
}
int x = 1;
if((new List {1, 2, 3}).Contains(x)) {}
- Largepublic 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));
}
静态类
中,您可以像这样使用它:if (x.In(1,2,3)) //whatever
n => object.Equals(n, value)
,因为 a) 它可以防止 null
,并且 b) 确保非值类型也有机会进行值相等性比较。(我认为使用 Contains()
而不是 Any()
也能达到同样的效果。) - dlevif(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-and-order-of-checking
int x = 1;
if((new List<int> {1, 2, 3}).Contains(x))
{
}
我完全是猜测的,如果我错了,请纠正代码:
(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]();
if
条件的全部内容:decisionTable[theNumberToTest]();
- Yair NevetContains
慢得多——建立字典的时间复杂度为O(n),与建立和扫描列表相同。 - Ryan MDictionary
只能建立一次。 - Yair Nevet以下回答涉及 C# 的可能未来版本 ;-) 如果您考虑切换到 Visual Basic,或者如果微软最终决定将 Select Case 语句引入 C#,它将如下所示:
Select Case X
Case 1, 2, 3
...
End Select
x == A || x == B || x == C || ... || x == Z
这样的语句时,你表达的意思是:"x是否在集合 {A, B, C, ..., Z} 中?" 因此,最清晰的语法应该是x in {A,B,C, ..., Z}
。当条件不同时,应使用||
运算符。 - Bakuriu