Left join in lambda expression notation

To use left join in lambda expression notation we have to use GroupJoin, SelectMany and DefaultIfEmpty() methods as follows:

var workerWithTitle = Context.worker.GroupJoin(
                Context.title,
                w => w.title_id,
                a => a.title_id,
                (w, a) => new { w, a });

            return workerWithTitle
                .SelectMany(w => w.a.DefaultIfEmpty(), (w, a) => new { Worker = w.w, Title = a })
                .Where(x => workerIds.Contains(x.Worker.WorkerId))
                .Select(x => new Worker
                    {
                        Title = x.Title.TitleName,
                        FirstName = x.Worker.FirstName,
                        LastName = x.Worker.LastName,
                        WorkerId = x.Worker.WorkerId
                    }).ToList();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s