我在LINQ中并不强大,但我正在努力熟悉GroupJoin
在以下代码中,我试图理解
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.AuthorId
,book => book.AuthorId
的含义是什么?这两行是否相当于
on a.AuthorId equals b.AuthorId
这一行的含义是什么:
(author, booksByAuthor) => new { Author = author.Name, Books = booksByAuthor }
我可以阅读/理解Join into语句,但对GroupJoin
有一些困难。感谢。
答案 0 :(得分: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 }
);
希望有所帮助。