在SQL中,可以使用如下语法:
SELECT *
FROM MY_TABLE
WHERE VALUE_1 IN (1, 2, 3)
C# 中是否有等效项? IDE 似乎将“in”识别为关键字,但我似乎无法找到有关它的任何信息。
那么,是否可以像下面那样做:
int myValue = 1;
if (myValue in (1, 2, 3))
// Do something
代替
int myValue = 1;
if (myValue == 1 || myValue == 2 || myValue == 3)
// Do something
最佳答案
如果您想编写 .In,那么您可以创建一个允许您这样做的扩展。
static class Extensions
{
public static bool In<T>(this T item, params T[] items)
{
if (items == null)
throw new ArgumentNullException("items");
return items.Contains(item);
}
}
class Program
{
static void Main()
{
int myValue = 1;
if (myValue.In(1, 2, 3))
// Do Somthing...
string ds = "Bob";
if (ds.In("andy", "joel", "matt"))
// Do Someting...
}
}
关于c# - 是否有 C# IN 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3164998/