如何在linq中编写此查询?

时间:2014-12-18 21:58:34

标签: sql linq

我知道可能有很多像这样的问题,但我遇到了麻烦

select * 
from [Group]
where GroupId not in 
(select GroupId
from CustomerGroup
where CustomerId = 189621)

我有myGroups = db.Groups.Where(e => e.GroupId),但我怎么说不在?

我很喜欢那里

var myGroups = from a in db.Groups
where!(from b in db.CustomerGroups
where b.CustomerId == customer.CustomerId )

2 个答案:

答案 0 :(得分:2)

var groupIds = from cg in db.CustomerGroups
               where cg.CustomerId == 189621
               select cg.GroupId;
var myGroups = from g in db.Groups
               where !groupIds.Contains(g.GroupId)
               select g;

首先需要清单取消资格。 NOT IN在LINQ中基本上是!(IEnumerable).Contains()(因为你要比较一组)。

答案 1 :(得分:1)

使用lambda表达式,你可能会这样做

var groupIds = db.CustomerGroups.Where(x => x.CustomerId == 189621).Select(x => x.GroupId);
var myGroups = db.CustomerGroups.Where(x => !groupIds.Contains(x.GroupId)).ToList();