

在第一張圖片中我有第一個查詢的結果,突出顯示的部分表示將通過在第二個查詢上應用過濾器來排除的行,在第二張圖片中我有查詢的結果select * from exlusion_table
我必須對第一個查詢進行更改以使其排除從第二個查詢中檢索到的專案
第一個查詢:
var u = from a in cx.VW_LIST
where (a.PRJ == codPrj) && (a.DATE > date_ || a.DATE == null || date_ == null)
&& (x.Contains(a.CODE) || x.Count() == 0)
select a)
第二個查詢:
var y = from esc in cx.EXCLUSION select esc
應修改第一個查詢以排除具有值 fcode = 第二個查詢的 fcode (在第二個查詢的 fscode = null 的情況下)或(fcode = 第二個查詢的 fcode && fscode = 第二個查詢的 fscode )
uj5u.com熱心網友回復:
您可以使用任何()。IE:
var u = from a in cx.VW_LIST
where (a.PRJ == codPrj)
&& (a.DATE > date_ || a.DATE == null || date_ == null)
&& (x.Contains(a.CODE) || x.Count() == 0)
&& (!cx.EXCLUSION.Any( y => x.fscode == y.fscode && x.fcode == y.fcode ))
select a)
uj5u.com熱心網友回復:
有兩種方法,一種是使用!和ANY()過濾在另一個串列中找到的記錄,這將編譯成WHERE NOT EXISTS(_exclusion_)過濾器運算式
var excluded = cx.EXCLUSION.AsQueryable();
var query = from vw in cx.VW_LIST
where vw.PRJ == codPrj
where vw.DATE == null || date_ == null || vw.DATE > date_
where !x.Any() || x.Contains(vw.CODE)
where !excluded.Any(esc => vw.fcode == esc.fcode
&& (esc.fscode == null || vw.fscode == esc.fscode))
select vw;
var results = query.ToList();
棘手的元素是排除表中的nullfor fscode,它需要充當通配符匹配,或否定fscode比較。
沒有必要將excluded查詢拆分為自己的查詢,我們可以cx.EXCLUSION直接參考表,它會產生完全相同的效果,這向您展示了一種封裝技術,用于以您可以輕松增加的方式構建 LINQ 查詢排除查找的復雜性,而不會造成整體查詢的混亂。
您可能還發現需要有條件地構建查詢,這是 fluent syntax 提供更模塊化方法的地方:
bool filterExcludedRecords = true;
...
var excluded = cx.EXCLUSION.AsQueryable();
var query = cx.VW_LIST.Where(vw => vw.PRJ == codPrj)
.Where(vw => vw.DATE == null || date_ == null || vw.DATE > date_)
.Where(vw => !x.Any() || x.Contains(vw.CODE));
if(filterExcludedRecords)
query = query.Where(vw => !excluded.Any(esc => vw.fcode == esc.fcode
&& (esc.fscode == null || vw.fscode == esc.fscode)));
var results = query.ToList();
外連接
另一種方法是使用LFET OUTER JOIN未找到排除匹配的地方:
var excluded = cx.EXCLUSION.AsQueryable();
var query = from vw in cx.VW_LIST
where vw.PRJ == codPrj
where vw.DATE == null || date_ == null || vw.DATE > date_
where !x.Any() || x.Contains(vw.CODE)
from esc in excluded.Where(e => vw.fcode == e.fcode
&& (e.fscode == null || vw.fscode == e.fscode))
.DefaultIfEmpty()
where esc.fscode == null
select vw;
var results = query.ToList();
它WHERE NOT EXISTS通常在性能方面更優越,OUTER JOIN在未優化的表中或當排除串列中的行數非常少而主表中的行數非常大時,可能會提供更好的回應。
為了完整性,我包含了這個查詢選項,眾所周知,您可以通過向from查詢添加新子句來創建簡單的外部連接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442867.html
