2016-04-26 43 views
1
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。Linq左连接lambda表达式和结果到列表

我已经试过下面这将导致生成错误:

无法隐式转换 “System.Collections.Generic.IEnumerable < ... BookOrder>到..BookOrder 的显式转换存在的类型(是你失踪5号线一投?)(红色 squigles上BKO)

我不能够改变书或BookOrder类,因为这是一个第三方,即我要参加下面列出的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(); 
+0

你可以改变'JoinModel'? – juharr

回答

1

这是你的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();