How do you implement the equivalent of SQL IN() using .net

前端 未结 9 1455
春和景丽
春和景丽 2020-12-09 16:24

In .net (c# or vb) expressions, how would you implement SQL\'s handy IN() functionality?

i.e. value in (1, 2, 4, 7)

rather than:

value = 1 or value =

9条回答
  •  醉梦人生
    2020-12-09 16:32

    if((new int[] {1, 2, 4, 7}).Contains(value))
    {
        // Do some work.
    }
    

    As others have pointed out, you could create an In() Extension method (I'll keep it generic so you can use it on any type):

    public static bool In(T this obj, IEnumerable col)
    {
        return col.Contains(obj);
    }
    

    So the initial example becomes:

    if(value.In(new int[] {1, 2, 4, 7}))
    {
        // Do some work.
    }
    

提交回复
热议问题