How do I translate the following in LINQ?
SELECT DISTINCT w.Worker_ID, w.Surname, w.FirstName, ps.JobNumber
FROM Worker w, ProjectSignatory ps
where w.Worker_ID = ps.Worker_ID
and ps.JobNumber
IN
(SELECT DISTINCT pa.JobNumber
FROM Worker w, PAAFRegister pa
where w.Worker_ID = pa.Worker_ID
and w.Worker_ID = @UserX)
I have seen anumber of posts which sugges that the .Contains function is a good idea, however since I am looking through a collection of results then based from what I have seen on other responses LINQ does not like it when people call .Contains on a collection.
I am trying to understand the workings of LINQ on the whole. I am relatively inexperienced. Any advice would be greatly appreciated.
EDIT: I have seen a few approaches and I am wondering if the following is a good start or would it be best achieved using a linge query using joins?
var sig = from w in db.Workers
join ps in db.ProjectSignatories
on w.Worker_ID equals ps.Worker_ID
select ps;
var paaf = from w in db.Workers
join pa in db.PAAFRegisters
on w.Worker_ID equals pa.Worker_ID
where w.Worker_ID == workerID
select w;
I am aware that this is incomplete and seves no purpose or makes no sense to what I am attempting to achieve. This was merely an example based on previous posts I have seen and wondering if the approach is suitable.
Thanks!
You're looking for the .Contains()
function.
First build up the inner filter set section of the query.
EG: The part that goes in the .Contains()
(in SQL terms the " ps.JobNumber IN (...)
" )
.Contains
function. Example:
C# SQL-like syntax:
var subSet = select JobNumber
from Workers
where Worker_ID == "UserX";
var result = select JobNumber
from Workers
where subSet.Contains(jobnumber);
LINQ chaining:
var subSet = Workers.Where(o => o.Worker_ID == "UserX")
.Select(o => o.JobNumber)
.Distinct();
var result = Workers.Where(o => subSet.Contains(o.JobNumber)).ToList();
You can create subselect's in LINQ.
var jobNumbers = select JobNumber from Workers where <your criteria, joins>
var myResult = select JobNumber from Workers where <your criteria, joins> and jobNumbers.Contains(JobNumber)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.