问题
There are at least two ways of doing LEFT OUTER JOIN in LINQ
class Customer
{
public int ID { get; set; }
public string Name { get; set; }
}
class Order
{
public int ID { get; set; }
public string Product { get; set; }
}
static void Main()
{
// Example customers.
var customers = new Customer[]
{
new Customer{ID = 5, Name = "Sam"},
new Customer{ID = 6, Name = "Dave"},
new Customer{ID = 7, Name = "Julia"},
new Customer{ID = 8, Name = "Sue"},
new Customer{ID = 9, Name = "Joe"}
};
// Example orders.
var orders = new Order[]
{
new Order{ID = 5, Product = "Book"},
new Order{ID = 6, Product = "Game"},
new Order{ID = 7, Product = "Computer"},
new Order{ID = 8, Product = "Shirt"},
new Order{ID = 8, Product = "TShirt"}
};
// First Way
var query = from c in customers
join o in orders on c.ID equals o.ID into co
from x in co.DefaultIfEmpty()
where x != null && x.Product == "Shirt"
select new {c, x};
// Second Way
var query2 = from c in customers
from o in orders
where c.ID == o.ID && o.Product == "Shirt"
select new {c, o};
}
I found a lot of examples of First Way (using 'into'), and that is the way I used to do my LEFT OUTER JOINS. Recently I found the second way, and looks like it is simpler. I tested and both of them produce the same result. Now my question are there any hidden differences, performance, or it is only syntactic sugar?
Thanks a lot.
回答1:
The First way should be used if you don't use the !=null check
A left outer join selects everything from the left table with all the items that match in the right table, if no matches exist in the right table the result is still returned but null for the values in the right table (linq translates this as the default value for the collection item type)
Both your queries effectively perform an inner join so they will be the same.
To get different results
// First Way
var query = from c in customers
join o in orders on c.ID equals o.ID into co
from x in co.DefaultIfEmpty()
where c.Id>5
select new {c, x};
// Second Way
var query2 = from c in customers
from o in orders
where c.ID == o.ID && c.ID > 5
select new {c, o};
来源:https://stackoverflow.com/questions/6790868/linq-left-outer-join-syntax-difference