DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

2 1

C# : Advanced LINQ - Use Subquery and Left Outer Join

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 
   };
Enter fullscreen mode Exit fullscreen mode

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay