LINQ to Entities中的“NOT IN”子句

有没有反正我可以创build一个不在子句中,像我将在SQL Server中的Linq实体

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

var exceptionList = new List<string> { "exception1", "exception2" }; var query = myEntities.MyEntity .Select(e => e.Name) .Where(e => !exceptionList.Contains(e.Name)); 

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

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

这假设了一个复杂的实体,在这个实体中,根据另一个表的某些属性排除某些特定的实体,并且希望不排除实体的名称。 如果你想要整个实体,那么你需要将exception构造成实体类的实例,以使它们满足默认的相等运算符(参见文档 )。

尝试:

 from p in db.Products where !theBadCategories.Contains(p.Category) select p; 

什么是你想要转换成Linq查询的SQL查询?

我有以下扩展方法:

  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; } 

用法:

 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)); 

直接传递值时非常有用:

 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")); 

我拿了一份清单,

 !MyList.Contains(table.columb.tostring()) 

注意:确保使用列表而不是Ilist

我使用更类似于SQL的方式创build它,我认为它更容易理解

 var list = (from a in listA.AsEnumerable() join b in listB.AsEnumerable() on a.id equals b.id into ab from c in ab.DefaultIfEmpty() where c != null select new { id = c.id, name = c.nome }).ToList();