LINQ to Entities中的"NOT IN"子句

dag*_*da1 46 c# linq-to-entities

反正我是否可以在Linq to Entities的 SQL Server中创建一个not in子句?

tva*_*son 92

如果您使用内存中的集合作为过滤器,则最好使用Contains()的否定.请注意,如果列表太长,这可能会失败,在这种情况下,您将需要选择另一个策略(请参阅下面的使用策略进行完全面向数据库的查询).

   var exceptionList = new List<string> { "exception1", "exception2" };

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Where(e => !exceptionList.Contains(e.Name));
Run Code Online (Sandbox Code Playgroud)

如果您基于另一个数据库查询使用排除Except可能是一个更好的选择.(这是LINQ to Entities中受支持的Set扩展的链接)

   var exceptionList = myEntities.MyOtherEntity
                                 .Select(e => e.Name);

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Except(exceptionList);
Run Code Online (Sandbox Code Playgroud)

这假设一个复杂的实体,您根据另一个表的某些属性排除某些实体,并且需要未排除的实体的名称.如果您想要整个实体,那么您需要将异常构造为实体类的实例,以便它们满足默认的相等运算符(请参阅docs).


yfe*_*lum 14

尝试:

from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;
Run Code Online (Sandbox Code Playgroud)

您要将哪个SQL查询转换为Linq查询?


Joa*_*Fdz 7

我有以下扩展方法:

    public static bool IsIn<T>(this T keyObject, params T[] collection)
    {
        return collection.Contains(keyObject);
    }

    public static bool IsIn<T>(this T keyObject, IEnumerable<T> collection)
    {
        return collection.Contains(keyObject);
    }

    public static bool IsNotIn<T>(this T keyObject, params T[] collection)
    {
        return keyObject.IsIn(collection) == false;
    }

    public static bool IsNotIn<T>(this T keyObject, IEnumerable<T> collection)
    {
        return keyObject.IsIn(collection) == false;
    }
Run Code Online (Sandbox Code Playgroud)

用法:

var inclusionList = new List<string> { "inclusion1", "inclusion2" };
var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsIn(inclusionList));

var exceptionList = new List<string> { "exception1", "exception2" };
var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsNotIn(exceptionList));
Run Code Online (Sandbox Code Playgroud)

直接传递值时非常有用:

var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsIn("inclusion1", "inclusion2"));

var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsNotIn("exception1", "exception2"));
Run Code Online (Sandbox Code Playgroud)