![](/img/trans.png)
[英]Need help with LINQ query that joins two tables containing periodic events
[英]Linq query without using Joins for two tables distinct value
表格1
合同 ID、供應商名稱、描述、用戶
表 2
合同編號、產品、部門
匹配條件:對於與表1匹配的所有合約ID,獲取它們的供應商名稱和合約ID
查詢結果輸出:Contract ID(Distinct),Vendor Name
下面使用內部連接的代碼,需要相同的輸出而不使用連接作為 linq 查詢 \\\\
select table1.Contract ID,table1.Vendor Name ,table2.Contract ID
from table1 as s1
inner join table2 as s2
on s1.Contract ID=s2.Contract ID
\\\
提前致謝
考慮到您只需要 Join 替代選擇不同的,您可以使用如下的內部查詢邏輯來編寫 LINQ SELECT 承包商 ID,供應商名稱 Where Contracterid in (Select distinct contract id from table2)
這里假設contractorId是表1中的主鍵
如果我理解正確,您想要檢索包含合同 ID 和供應商名稱的對象集合,沒有重復,其合同 ID 見表 2。
不清楚您是使用 Linq to objects、Linq to Entities 還是任何其他 Linq 風格,這將對如何最好地構造特定目的的查詢產生有意義的影響。
但作為第一個提示,這里有一種無需加入 Linq 即可執行此操作的方法:
// Get a list of all distinct Contract Ids in Table 2
var AllTable2ContractIds = Table2
.Select(e => e.ContractId)
.Distinct()
.ToList();
// With Table 1
// Keep only entries whose contract Id is found in the list just contructed above.
// transform it to keep Contract Id and Vendor Name.
// The use of ToList() at the end is not mandatory.
// It depends if you want to materialize the result or not.
var Result = Table1
.Where(e => AllTable2ContractIds.Contains(e.ContractId))
.Select(e => new
{
e.ContractId,
e.VendorName
})
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.