Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to join in Linq

I was working with the first method below, but then I found the second and want to know the difference and which is best.

What is the difference between:

from a in this.dataContext.reglements
join b in this.dataContext.Clients on a.Id_client equals b.Id 
select...

and

from a in this.dataContext.reglements
from b in this.dataContext.Clients
where a.Id_client == b.Id 
select...
like image 291
Akrem Avatar asked Jul 08 '11 18:07

Akrem


People also ask

How do you do Joins in LINQ?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.

What type of join is LINQ join?

In LINQ, Join() operators are used to join the two or more lists/collections and get the matched data from the collection based on the specified conditions. The behavior and functionality of Join() operators are the same as SQL joins.

How Use left and right join in LINQ?

In LINQ, LEFT JOIN or LEFT OUTER JOIN is used to return all the records or elements from the left side collection and matching the elements from the right side of the collection. In LINQ, to achieve the LEFT Join behavior, it is mandatory to use the "INTO" keyword and "DefaultfEmpty()" method.


2 Answers

I created a test case to test out the difference, and in your scenerio it turns out they are the same.

My test example used AdventureWorks but basically there is an association between

Products->CategoryId->Categories

var q = (
    from p in Products
    from c in Categories
        where p.CategoryID==c.CategoryID
    select p
);

q.ToList();

Produces this SQL:

SELECT [t0].[ProductID], [t0].[ProductName], [t0].[CategoryID]
    FROM [Products] AS [t0], [Categories] AS [t1]
WHERE [t0].[CategoryID] = ([t1].[CategoryID])

var q2 = (
    from p in Products 
    join c in Categories 
        on p.CategoryID equals c.CategoryID
    select p);

q2.ToList();

Produces this sql:

SELECT [t0].[ProductID], [t0].[ProductName], [t0].[CategoryID]
FROM [Products] AS [t0]
INNER JOIN [Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[CategoryID])
like image 170
Nix Avatar answered Sep 23 '22 12:09

Nix


The difference between these two syntaxes will be in the way they are translated into SQL. You can trace Entity Framework or LINQ to SQL to determine the SQL:

LINQ to SQL: http://www.reflectionit.nl/Blog/PermaLinkcba15978-c792-44c9-aff2-26dbcc0da81e.aspx

Check the resulting SQL to determine if there are any differences that could affect performance.

like image 40
Dave Swersky Avatar answered Sep 21 '22 12:09

Dave Swersky