1

I am not strong in LINQ but I am trying to get familiar with GroupJoin

In the following code, which I am trying to understand

var result = authors.GroupJoin(books,
                               author => author.AuthorId,
                               book => book.AuthorId,
                               (author, booksByAuthor) => 
                                new { Author = author.Name, Books = booksByAuthor });

which was rewritten from this join into code

var result = from a in authors
             join b in books on a.AuthorId equals b.AuthorId into booksByAuthor
             select new { Author = a.Name, Books = booksByAuthor };

I am confused by the syntax in the GroupJoin. I understand that the tables authors is joined with books, but what is the meaning of the next few lines?

For example, what is the meaning of author => author.AuthorId, book => book.AuthorId? Is these two lines the equivalent of

on a.AuthorId equals b.AuthorId 

?

And what is the meaning of this line:

(author, booksByAuthor) => new { Author = author.Name, Books = booksByAuthor } 

I can read/understand the Join into statement but having some difficulties with the GroupJoin. Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user1250264
  • 897
  • 1
  • 21
  • 54

1 Answers1

1

Probably you get confused because the two examples use different aliases for one and the same things. So let fix that:

var result = from a in authors
             join b in books on a.AuthorId equals b.AuthorId into booksByAuthor
             select new { Author = a.Name, Books = booksByAuthor };

and

var result =
    // authors join books 
    authors.GroupJoin(books,
    // on a.AuthorId equals b.AuthorId
    a => a.AuthorId, b => b.AuthorId,
    // select new { Author = a.Name, Books = booksByAuthor }
    (a, booksByAuthor) => new { Author = a.Name, Books = booksByAuthor }
);

Hope that helps.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343