如何使用.net实现SQL IN()的等价物

Pet*_*r C 19 .net c# sql vb.net sql-server

在.net(c#或vb)表达式中,您将如何实现SQL的便捷IN()功能?

即(1,2,4,7)中的值

而不是:

value = 1或value = 2或value = 4或value = 7

Mic*_*sov 25

using System;
using System.Linq;

static class SqlStyleExtensions
{
    public static bool In(this string me, params string[] set)
    {
       return set.Contains(me);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

if (Variable.In("AC", "BC", "EA"))
{

} 
Run Code Online (Sandbox Code Playgroud)

  • 通用版本 - public static bool In <T>(this T me,params T [] List) (3认同)

was*_*atz 13

我为此做了一个扩展方法,我觉得非常有用.但是,它只包含现有IEnumerable.Contains()函数的语法糖.

/// <summary>
/// Returns true if the value is represented in the provided enumeration.
/// </summary>
/// <typeparam name="T">Type of the value</typeparam>
/// <param name="obj">The object to check if the enumeration contains</param>
/// <param name="values">The enumeration that might contain the object</param>
/// <returns>True if the object exists in the enumeration</returns>
public static bool In<T>(this T obj, IEnumerable<T> values) {
    return values.Contains(obj);
}
Run Code Online (Sandbox Code Playgroud)

编辑:有人打败了我,该死的.我会留在这里发帖,因为它是一个更通用的版本.


jim*_*lan 8

我知道这里有很多答案,但这是我对这个主题的看法,每天都在SubSonic中使用.这是一种扩展方法:

public static IQueryable<T> WhereIn<T, TValue>(
                this IQueryable<T> query,
                Expression<Func<T, TValue>> selector, 
                params TValue[] collection) where T : class
{
    if (selector == null) throw new ArgumentNullException("selector");
    if (collection == null) throw new ArgumentNullException("collection");
    ParameterExpression p = selector.Parameters.Single();

    if (!collection.Any()) return query;

    IEnumerable<Expression> equals = collection.Select(value =>
       (Expression)Expression.Equal(selector.Body,
            Expression.Constant(value, typeof(TValue))));

    Expression body = equals.Aggregate(Expression.Or);
    return query.Where(Expression.Lambda<Func<T, bool>>(body, p));
}
Run Code Online (Sandbox Code Playgroud)

和WhereNotIn:

public static IQueryable<T> WhereNotIn<T, TValue>(
                this IQueryable<T> query, 
                Expression<Func<T, TValue>> selector, 
                params TValue[] collection) where T : class
{
    if (selector == null) throw new ArgumentNullException("selector");
    if (collection == null) throw new ArgumentNullException("collection");
    ParameterExpression p = selector.Parameters.Single();

    if (!collection.Any()) return query;

    IEnumerable<Expression> equals = collection.Select(value =>
       (Expression)Expression.NotEqual(selector.Body,
            Expression.Constant(value, typeof(TValue))));

    Expression body = equals.Aggregate(Expression.And);

    return query.Where(Expression.Lambda<Func<T, bool>>(body, p));
}
Run Code Online (Sandbox Code Playgroud)

用法:

var args = new [] { 1, 2, 3 };
var bookings = _repository.Find(r => r.id > 0).WhereIn(x => x.BookingTypeID, args);
// OR we could just as easily plug args in as 1,2,3 as it's defined as params
var bookings2 = _repository.Find(r => r.id > 0).WhereIn(x => x.BookingTypeID, 1,2,3,90);

var bookings3 = _repository.Find(r => r.id > 0).WhereNotIn(x => x.BookingTypeID, 20,30,60);
Run Code Online (Sandbox Code Playgroud)

这真的让我每次回顾时都会微笑:)

吉姆

[编辑] - 最初源自SO,但修改为使用iqueryable和params: 'Contains()'解决方法使用Linq to Entities?


Jus*_*ner 6

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

正如其他人所指出的那样,你可以创建一个In()扩展方法(我将它保持通用,这样你就可以在任何类型上使用它):

public static bool In<T>(T this obj, IEnumerable<T> col)
{
    return col.Contains(obj);
}
Run Code Online (Sandbox Code Playgroud)

所以最初的例子变成:

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


Car*_*lin 6

或使用System.Linq......

(VB.NET)

Enumerable.Contains({1, 2, 4, 7}, value)
Run Code Online (Sandbox Code Playgroud)

要么

{1, 2, 4, 7}.Contains(value)
Run Code Online (Sandbox Code Playgroud)

(C#)

Enumerable.Contains(new int[]{1, 2, 4, 7}, value);
Run Code Online (Sandbox Code Playgroud)

要么

new int[] {1, 2, 4, 7}.Contains(value);
Run Code Online (Sandbox Code Playgroud)