C# 如何使用 Linq“不在”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15424770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:47:17  来源:igfitidea点击:

how to use Linq " NOT IN"

c#.netlinq

提问by user1348351

I'm using Entity Framework
So I want to write a sql command using two tables - tblContractor and tbSiteByCont tables. It looks like this in SQL

我正在使用实体框架
所以我想使用两个表编写一个 sql 命令 - tblContractor 和 tbSiteByCont 表。在 SQL 中看起来像这样

SELECT     PKConID, Fname, Lname
FROM         tblContractor
WHERE     (PKConID NOT IN
                          (SELECT     FKConID
                            FROM          tbSiteByCont
                            WHERE      (FKSiteID = 13)))

but I don't know how to write in Linq.

但我不知道如何在 Linq 中写作。

I tried like this

我试过这样

  var query1 = from s in db.tblSiteByConts   
                        where  s.FKSiteID == id
                        select s.FKConID;


            var query = from c in db.tblContractors   
                        where c.PKConID != query1.Any()
                        select Contractor;

But this doesn't work. So how should I write it? What is the procedure? I'm new to Linq.

但这不起作用。那我应该怎么写呢?程序是什么?我是 Linq 的新手。

采纳答案by John Woo

var _result = from a in tblContractor
              where !(from b in tbSiteByCont
                        where FKSiteID  == 13
                        select b.FKConID)
                        .Contains(a.PKConID)
              select a;

or

或者

var siteLst = tbSiteByCont.Where(y => y.FKSiteID == 13)
                          .Select(x => x.FKConID);
var _result = tblContractor.Where(x => !siteLst.Contains(x.PKConID));

回答by John Andrade

I'd use a HashSet, it ensures you only evaluate the sequence once.

我会使用 HashSet,它确保您只对序列进行一次评估。

var result = from p in tblContractor
                      let hasht = new HashSet<int>((from b in tbSiteByCont
                                                    where b.FKSiteID == 13
                                                    select b.PKConID).Distinct())
                      where !hasht.Contains(p.PKConID)
                      select p;

回答by BeSome

may this work too

这也可以工作

var _result = from a in tblContractor
                       .Where(c => tbSiteByCont
                       .Count(sbc => sbc.FKSiteID == 13 && c.PKConID == sbc.FKConID) == 0)