C# 如何使用 LINQ 选择不存在的地方?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9031008/
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
How to SELECT WHERE NOT EXIST using LINQ?
提问by fiberOptics
I have to list all "shift" data to be assigned to an "employee" but shift data must not be included if it is already existing in employee's data. Let's see the image sample.
我必须列出要分配给“员工”的所有“班次”数据,但如果班次数据已存在于员工数据中,则不得包括该数据。让我们看看图像示例。


This query solves the problem. I found this here:
Scott's Blog
这个查询解决了这个问题。我在这里找到了这个:
斯科特的博客
select * from shift where not exists
(select 1 from employeeshift where shift.shiftid = employeeshift.shiftid
and employeeshift.empid = 57);
Let's see the result:
让我们看看结果:


Now my question is, how could I make this in linQ ? I'm using entity framework.
Hope someone could help. Thanks a lot!!!
现在我的问题是,我怎么能在 linQ 中做到这一点?我正在使用实体框架。
希望有人能帮忙。非常感谢!!!
采纳答案by Arsen Mkrtchyan
from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;
Hope this helps
希望这可以帮助
回答by hyp
The outcome sql will be different but the result should be the same:
结果 sql 会有所不同,但结果应该是相同的:
var shifts = Shifts.Where(s => !EmployeeShifts.Where(es => es.ShiftID == s.ShiftID).Any());
回答by Matt Roberts
How about..
怎么样..
var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)
Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest
编辑:这将为您提供有关联员工班次的班次(由于加入)。对于“不存在”,我会做@ArsenMkrt 或@hyp 建议的事情
回答by Ceridan
First of all, I suggest to modify a bit your sql query:
首先,我建议修改一下你的 sql 查询:
select * from shift
where shift.shiftid not in (select employeeshift.shiftid from employeeshift
where employeeshift.empid = 57);
This query provides same functionality. If you want to get the same result with LINQ, you can try this code:
此查询提供相同的功能。如果你想用 LINQ 得到同样的结果,你可以试试这个代码:
//Variable dc has DataContext type here
//Here we get list of ShiftIDs from employeeshift table
List<int> empShiftIds = dc.employeeshift.Where(p => p.EmpID = 57).Select(s => s.ShiftID).ToList();
//Here we get the list of our shifts
List<shift> shifts = dc.shift.Where(p => !empShiftIds.Contains(p.ShiftId)).ToList();
回答by julio
Dim result2 = From s In mySession.Query(Of CSucursal)()
Where (From c In mySession.Query(Of CCiudad)()
From cs In mySession.Query(Of CCiudadSucursal)()
Where cs.id_ciudad Is c
Where cs.id_sucursal Is s
Where c.id = IdCiudad
Where s.accion <> "E" AndAlso s.accion <> Nothing
Where cs.accion <> "E" AndAlso cs.accion <> Nothing
Select c.descripcion).Single() Is Nothing
Where s.accion <> "E" AndAlso s.accion <> Nothing
Select s.id, s.Descripcion

