LEFT OUTER JOIN in LINQ

后端 未结 22 2518
臣服心动
臣服心动 2020-11-21 04:49

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Corr

相关标签:
22条回答
  • 2020-11-21 05:19

    Easy way is to use Let keyword. This works for me.

    from AItem in Db.A
    Let BItem = Db.B.Where(x => x.id == AItem.id ).FirstOrDefault() 
    Where SomeCondition
    Select new YourViewModel
    {
        X1 = AItem.a,
        X2 = AItem.b,
        X3 = BItem.c
    }
    

    This is a simulation of Left Join. If each item in B table not match to A item , BItem return null

    0 讨论(0)
  • 2020-11-21 05:20

    Here's an example if you need to join more than 2 tables:

    from d in context.dc_tpatient_bookingd
    join bookingm in context.dc_tpatient_bookingm 
         on d.bookingid equals bookingm.bookingid into bookingmGroup
    from m in bookingmGroup.DefaultIfEmpty()
    join patient in dc_tpatient
         on m.prid equals patient.prid into patientGroup
    from p in patientGroup.DefaultIfEmpty()
    

    Ref: https://stackoverflow.com/a/17142392/2343

    0 讨论(0)
  • 2020-11-21 05:20

    Here is a fairly easy to understand version using method syntax:

    IEnumerable<JoinPair> outerLeft =
        lefts.SelectMany(l => 
            rights.Where(r => l.Key == r.Key)
                  .DefaultIfEmpty(new Item())
                  .Select(r => new JoinPair { LeftId = l.Id, RightId = r.Id }));
    
    0 讨论(0)
  • 2020-11-21 05:21

    Take a look at this example. This query should work:

    var leftFinal = from left in lefts
                    join right in rights on left equals right.Left into leftRights
                    from leftRight in leftRights.DefaultIfEmpty()
                    select new { LeftId = left.Id, RightId = left.Key==leftRight.Key ? leftRight.Id : 0 };
    
    0 讨论(0)
  • 2020-11-21 05:25

    As stated on:

    101 LINQ Samples - Left outer join

    var q =
        from c in categories
        join p in products on c.Category equals p.Category into ps
        from p in ps.DefaultIfEmpty()
        select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
    
    0 讨论(0)
  • 2020-11-21 05:25

    Using lambda expression

    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   
      });
    
    0 讨论(0)
提交回复
热议问题