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.


   1:  class User
   2:  {
   3:       public int UserID { get; set; }
   4:       public string Name{ get; set; }
   5:  }
   7:  class Order
   8:  {
   9:       public int OrderID { get; set; }
  10:       public int UserID { get; set; }
  11:       public int ProductID { get; set; }
  12:  }
  14:  List<User> users = UserService.List();
  15:  List<Order> orders = OrderService.ListByUser(userID);
  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();

11 November 2010

How to use ASP.Net validators with a User Control?

ASP.Net validators and user controls (ascx) are great. They save us a lot of time.
But when we mix a User Control and a ASP.Net validator the following error occurs:

Control 'UserSelector' referenced by the ControlToValidate property of 'rvUserSelector' cannot be validated.

The solution to this problem is to use the attribute ValidationProperty on the User Control:

public partial class UserSelector : UserControl

In this example the UserID property of the User Control is used by the validators to perform the validation.

To end, I would like to thank you Alexandre Simões for his help in solving this issue.