LINQ is great tool to write query for any data source, but I sometime have no idea how to write correct code to execute what I want to run.
I am writing this blog for myself as I am sure to forget this sooner or later :)
Left outer join
Perform left outer joins explains details of how to write left outer join with LINQ.
The point is to use into
and DefaultIfEmpty()
method on it.
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new
{
person.FirstName,
PetName = subpet?.Name ?? String.Empty
};
Subquery
Subquery is more straight forward. We can use subquery both in new
section and in
section. If query gets longer, we can also define subquery as separate query and use it in main query.
Top comments (0)