本文介绍了有C#IN运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL中,您可以使用以下语法:

In SQL, you can use the following syntax:

SELECT *
FROM MY_TABLE
WHERE VALUE_1 IN (1, 2, 3)

C#中是否有等效项? IDE似乎将"in"识别为关键字,但我似乎找不到任何信息.

Is there an equivalent in C#? The IDE seems to recognise "in" as a keyword, but I don't seem to be able to find any information on it.

因此,是否可以执行以下操作:

So, is it possible to do something like the following:

int myValue = 1;
if (myValue in (1, 2, 3))
    // Do something

代替

int myValue = 1;
if (myValue == 1 || myValue == 2 || myValue == 3)
    // Do something

推荐答案

如果您想编写.那么您可以创建一个扩展名,以便执行此操作.

If you wanted to write .In then you could create an extension that allows you to do that.

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#IN运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:11