Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the 'equals' operator in LINQ joins?

Tags:

.net

linq

Why doesn't link simply use the == operator in joins if t can use it in a 'where' clause?

like image 563
ProfK Avatar asked Oct 25 '09 10:10

ProfK


People also ask

How does join work 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.

Which operator in LINQ is equivalent to cross join of SQL?

Cross join is also known as full join.

Can we do Joins in LINQ?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.

What are LINQ joins?

Join Method (System. Linq) Correlates the elements of two sequences based on matching keys.


1 Answers

The two sides of the equality in a join are treated as two separate lambda expressions which generate the keys for the two sequences.

from category in categories
join prod in products on category.ID equals prod.CategoryID

categories.Join(products,
                category => category.ID,
                prod => prod.CategoryID,
                (category, prod) => new { Category = category, Product=prod });

Using the equals keyword makes it unabmiguous where one lambda ends and the other starts. For a where clause, on the other hand, there's a single lambda expression which decides whether each item matches:

from prod in products
where prod.CategoryID == 1

products.Where( prod => prod.CategoryID == 1 )

In theory, joins could have been implemented with a single lambda as

from category in categories
join prod in products on category.ID == prod.CategoryID

categories.Join(products,
                (category, prod) => category.ID == prod.CategoryID,
                (category, prod) => new { Category = category, Product=prod });

However, by computing two keys and doing the comparison itself, LINQ can use hash tables to compute the join more efficiently than if it had to execute an arbitrary comparison for every pair of elements.

like image 185
stevemegson Avatar answered Sep 28 '22 19:09

stevemegson