Jakeuj's Notes master Help

Linq Left Join (GroupJoin + SelectMany) Repository {id="Linq-Left-Join-GroupJoin-SelectMany-Repository"}

Repository Linq LeftJoin (GroupJoin + SelectMany) and Join

假設有兩個倉儲 A,B

要用A.bId去跟B.Id為依據

去拿B.Name欄位

最後合併 A.Id與B.Name

成為 cDto 作為資料傳輸物件輸出

  • Left Join (GroupJoin + Select) 子集合選擇特定欄位

var joinQuery = order .GroupJoin(orderStatus, o => o.Id, s => s.Id, (o, s) => new { o.Id, data = s.Select(x => new { x.Item, x.Qty } ) } ) .Where(x => x.data.Any()) .ToList();
1665481478 png
  • Left Join (GroupJoin + SelectMany) 攤平子集合

var joinQuery = _aRepository.GetAll() .GroupJoin(_bRepository.GetAll(), a => a.bId, b => b.Id, (a,b) => new{a,b}) .SelectMany(result => result.b.DefaultIfEmpty(), (x, y) => new cDto{ Id = x.a.Id, Name = y.Name ?? "N/A" });
  • Join  (innerJoin)

var joinQuery = _aRepository.GetAll() .Join(_bRepository.GetAll(), a=>a.bId, b=>b.Id, (a,b)=>new cDto{ Id = a.Id, Name = b.Name });

B倉儲只要沒有A的bID,該筆資料就不會出現在結果

參照: LINQ學習筆記(7)實作Left join(1) Join與Group join

Jakeuj

PS5

  • Join

  • Linq

  • Repository

  • 回首頁

本文章從點部落遷移至 Writerside

13 October 2025