[英]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; }
}
Trying to write a lambda expression which will do a left join and return a list.尝试编写一个 lambda 表达式,它将执行左连接并返回一个列表。 The list should contain Books, but BookOrder can be null.该列表应包含 Books,但 BookOrder 可以为 null。
I have tried following which results in build error :我试过以下导致构建错误:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<...BookOrder> to ..BookOrder An explicit conversion exists (are you missing a cast?) on Line 5 (red squigles on bko)无法将类型 'System.Collections.Generic.IEnumerable<...BookOrder> 隐式转换为 ..BookOrder 第 5 行(bko 上的红色波浪线)存在显式转换(您是否缺少演员表?)
I am not able to change Book or BookOrder classes as this is a 3rd party, ie I have to join on the 3 conditions listed below.我无法更改 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();
Here's your linq:这是你的 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();
And here you go with your lambda expression version在这里,您可以使用 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.