What are different types of joins in LINQ?

LINQ has a JOIN query operator that provides SQL JOIN like behavior and syntax. There are four types of Joins in LINQ.

  1. INNER JOIN – Inner join returns only those records or rows that match or exists in both the tables.
    DataContext context = new DataContext();
    var q = (from pd in context.Products join od in context.Orders on pd.ProductID equals od.ProductID orderby od.OrderID select new {
    	od.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, od.Quantity, od.Price,
    }).ToList();
  2. GROUP JOIN– When a join clause use an INTO expression, then it is called a group join. A group join produces a sequence of object arrays based on properties equivalence of left collection and right collection. If right collection has no matching elements with left collection then an empty array will be produced.
    DataContext context = new DataContext();
    var q = (from pd in context.tblProducts join od in context.tblOrders on pd.ProductID equals od.ProductID into t orderby pd.ProductID select new {
    	pd.ProductID, pd.Name, pd.UnitPrice, Order = t
    }).ToList();

    Basically, GROUP JOIN is like as INNER-EQUIJOIN except that the result sequence is organized into groups.

  3. LEFT OUTER JOIN – LEFT JOIN returns all records or rows from left table and from right table returns only matched records. If there are no columns matching in the right table, it returns NULL values.
    In LINQ to achieve LEFT JOIN behavior, it is mandatory to use “INTO” keyword and “DefaultIfEmpty()” method. We can apply LEFT JOIN in LINQ like as:

    DataContext context = new DataContext();
    var q = (from pd in context.tblProducts join od in context.tblOrders on pd.ProductID equals od.ProductID into t from rt in t.DefaultIfEmpty() orderby pd.ProductID select new {
    	OrderID = rt.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, rt.Quantity, rt.Price,
    }).ToList();
  4. CROSS JOIN– Cross join is a Cartesian join means Cartesian product of both the tables. This join does not need any condition to join two tables. This join returns records or rows that are multiplication of record number from both the tables’ means each row on left table will relate to each row of right table.
    In LINQ to achieve CROSS JOIN behavior, there is no need to use Join clause and where clause. We will write the query as shown below.

    DataContext context = new DataContext();
    var q = from c in context.Customers from o in context.Orders select new {
    	c.CustomerID, c.ContactName, o.OrderID, o.OrderDate
    };

     

Tagged , . Bookmark the permalink.

Leave a Reply