2015-12-30 52 views
1

我不堅強的LINQ,但我想熟悉GroupJoin需要解釋有關LINQ羣組加入語法

在下面的代碼,我想了解

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

這是從改寫這種加入到代碼

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 }; 

我通過在GroupJoin語法混淆。我知道表格的作者和書籍一起,但接下來幾行的含義是什麼?

例如,author => author.AuthorIdbook => book.AuthorId是什麼意思?這兩條線是否相當於

on a.AuthorId equals b.AuthorId 

什麼是此行的意義:

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

我可以讀/理解加入到語句,但具有與該GroupJoin一些困難。謝謝。

+0

可能[重複](http://stackoverflow.com/a/15599143/861716)。 –

回答

1

可能你會感到困惑,因爲這兩個例子對於同一件事物使用不同的別名。因此,讓我們解決這個問題:

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 }; 

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 } 
); 

希望有所幫助。