15 November 2010

LINQ To Objects: Left Join

Linq to Objects is a powerfull technology. One of the many features it has it the power to perform a left join between objects. The syntax for a left join is not like in SQL.

A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. Calling DefaultIfEmpty on the results of a group join returns the result of a left join.

Example:


   1:  class User
   2:  {
   3:       public int UserID { get; set; }
   4:       public string Name{ get; set; }
   5:  }
   6:   
   7:  class Order
   8:  {
   9:       public int OrderID { get; set; }
  10:       public int UserID { get; set; }
  11:       public int ProductID { get; set; }
  12:  }
  13:   
  14:  List<User> users = UserService.List();
  15:  List<Order> orders = OrderService.ListByUser(userID);
  16:   
  17:  var q = from o in orders 
  18:          join u in users on o.UserID = u.UserID into joinedUsers
  19:          from UserOrders in joinedUsers.DefaultIfEmpty()
  20:          select new UserOrder()
  21:          {
  22:              OrderID = o.OrderID,
  23:              ProductID = o.ProductID,
  24:              Name = UserOrders.Name
  25:          }
  26:  var result = q.ToList();

No comments: