简体   繁体   English

linq中的左外连接

[英]Left outer join in linq

I have the following query but i have no idea on how to do a left outer join on table 1. 我有以下查询,但我不知道如何在表1上进行左外连接。

var query = (from r in table1
             join f in table2
                 on r.ID equals f.ID
             select new
             {     
                 r.ID, 
                 r.FirstName,
                 r.LastName,
                 FirstNameOnRecord = 
                     (f != null ? f.FirstName : string.Empty),
                 LastNameOnRecord = 
                     (f != null ? f.LastName : string.Empty),
                 NameChanged = 
                     (f != null 
                         ? (f.FirstName.CompareTo(r.FirstName) == 0 
                             && f.LastName.CompareTo(r.LastName) == 0) 
                         : false)
             }).ToList();

这是左外连接的一个很好的细分。

Refer this or this examples to learn more and your case it would be something like this- 请参阅示例或示例以了解更多信息以及您的情况将会是这样的 -

var query = from r in table1
            join f in table2
            on r.ID equals f.ID into g
            from f in g.DefaultIfEmpty()
             select new
             {     
                r.ID
                , r.FirstName
                , r.LastName
                , FirstNameOnRecord = (f != null ? f.FirstName : string.Empty)
                , LastNameOnRecord = (f != null ? f.LastName : string.Empty)
                , NameChanged = (f != null ? (f.FirstName.CompareTo(r.FirstName) == 0 
                &&  f.LastName.CompareTo(r.LastName) == 0) : false)
              }).ToList();

Have you seen these examples ? 你见过这些例子吗? You're probably interested in this part about Left Outer Join in Linq. 你可能对这部分关于Linq的Left Outer Join感兴趣。

Using lambda expression 使用lambda表达式

db.Categories    
  .GroupJoin(
     db.Products,
     Category => Category.CategoryId,
     Product => Product.CategoryId,
     (x, y) => new { Category = x, Products = y })
  .SelectMany(
     xy => xy.Products.DefaultIfEmpty(),
     (x, y) => new { Category = x.Category, Product = y })
  .Select(s => new
  {
     CategoryName = s.Category.Name,     
     ProductName = s.Product.Name   
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM