[英]Linq left join lambda expression and result to a list
public class JoinModel
{
public Book Book { get; set; }
public BookOrder BookOrder { get; set; }
}
public class Book
{
public int BookID { get; set; }
public string UniqueID{ get; set; }
public int Year { get; set; }
public int BookNumber { get; set; }
public int Value { get; set; }
}
public class BookOrder
{
public int BookOrderID { get; set; }
public string UniqueID{ get; set; }
public int Year { get; set; }
public int BookNumber { get; set; }
public DateTime OrderDate { get; set; }
}
嘗試編寫一個 lambda 表達式,它將執行左連接並返回一個列表。 該列表應包含 Books,但 BookOrder 可以為 null。
我試過以下導致構建錯誤:
無法將類型 'System.Collections.Generic.IEnumerable<...BookOrder> 隱式轉換為 ..BookOrder 第 5 行(bko 上的紅色波浪線)存在顯式轉換(您是否缺少演員表?)
我無法更改 Book 或 BookOrder 類,因為這是第 3 方,即我必須加入下面列出的 3 個條件。
List<JoinModel> lstJoinModel = new List<JoinModel>();
Line 1 - lstJoinModel = Context.Books
Line 2 - .GroupJoin(Context.BookOrder,
Line 3 - bk => new { bk.UniqueID, bk.Year, bk.PostingId },
Line 4 - bko => new { bko.UniqueID, bko.Year, bko.BookNumber },
Line 5 - (bk, bko) => new JoinModel { Book = bk, BookOrder = bko })
Line 6 - .Where(r => r.Book.Value > 0).ToList();
這是你的 linq:
List<JoinModel> lstJoinModel = (from bk in Context.Books
join bko in Context.BookOrder on new { bk.UniqueID, bk.Year, bk.BookNumber } equals new { bko.UniqueID, bko.Year, bko.BookNumber }
into bd
from bd2 in bd.DefaultIfEmpty()
where bk.Value > 0
select new JoinModel { Book = bk, BookOrder = bd2 }
).ToList();
在這里,您可以使用 lambda 表達式版本
List<JoinModel> lstJoinModel = Context.Books.GroupJoin(Context.BookOrder,
bk => new { bk.UniqueID, bk.Year, bk.BookNumber },
bko => new { bko.UniqueID, bko.Year, bko.BookNumber },
(x, y) => new { Book = x, BookOrder = y })
.SelectMany(x => x.BookOrder.DefaultIfEmpty(),
(x, y) => new JoinModel
{
Book = x.Book,
BookOrder = y
})
.Where(r => r.Book.Value > 0).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.