I am looking for the Linq-equivalent of the following SQL:
SELECT t0.Fk_CompanyId, t0.CheckedUtc, t0.IsBlocking
FROM MyTable t0
LEFT OUTER JOIN MyTable t1
ON t0.Fk_CompanyId = t1.Fk_CompanyId AND t0.CheckedUtc < t1.CheckedUtc
WHERE t1.Fk_CompanyId IS NULL
AND t0.CheckedUtc IS NOT NULL
The closest I've got with Linq is:
from t0 in MyTable
join t1 in MyTable on t0.Fk_CompanyId equals t1.Fk_CompanyId into t1tmp
from t1 in t1tmp.DefaultIfEmpty()
where t1.Fk_CompanyId == null && t0.CheckedUtc != null && t0.CheckedUtc < t1.CheckedUtc
select new { cid = t0.Fk_CompanyId, cuct = t0.CheckedUtc, isbl = t0.IsBlocking }
... which produces the following SQL (reformatted slightly):
SELECT t0.Fk_CompanyId, t0.CheckedUtc, t0.IsBlocking
FROM MyTable AS t0
LEFT OUTER JOIN MyTable AS t1
ON t0.Fk_CompanyId = t1.Fk_CompanyId
WHERE (t1.Fk_CompanyId IS NULL)
AND (t0.CheckedUtc IS NOT NULL)
AND (t0.CheckedUtc < t1.CheckedUtc)
These are not exactly equivalent. (The t0.CheckedUtc < t1.CheckedUtc
is pushed to the WHERE
.) When I outer-left-join on t0.CheckedUtc < t1.CheckedUtc
, this produces NULL values on the right-hand-side of the join. When I filter with WHERE
instead, this removes all the NULL values that I am interested in.
Perspective: I am trying to find the rows in MyTable with the most recent CheckedUtc , if there are any non-NULL ones, grouped by Fk_CompanyId . And I want one row for each Fk_CompanyId . There are several "possible duplicates" that only deal with finding the most recent CheckedUtc s (but not their respective rows), or assume that CheckedUtc is NOT NULL.
So: How do I perform the equivalent of a join on a non-equals predicate in Linq?
Try this
from t0 in MyTable
From t1 in MyTable( x=>x.Fk_CompanyId=t0.Fk_CompanyId && x.CheckedUtc > t0.CheckedUtc ).DefaultIfEmpty()
where t1.Fk_CompanyId == null && t0.CheckedUtc != null
select new { cid = t0.Fk_CompanyId, cuct = t0.CheckedUtc, isbl = t0.IsBlocking }
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.