带有let运算符的查询的linq版本

时间:2012-06-24 07:28:20

标签: c# linq entity-framework linq-to-sql c#-4.0

我有这样的疑问:

SELECT au_lname,der.col FROM authors INNER JOIN (SELECT t.au_id, COUNT(title_id) AS 'col'
                       FROM titleauthor t GROUP BY t.au_id) der ON authors.au_id=der.au_id

我想用let运算符写这个。我怎么能这样做?

感谢

1 个答案:

答案 0 :(得分:2)

我认为没有充分的理由在这里使用let。您可以使用群组加入。

var query = from author in authors
            join title in titleAuthor on author.AuthorId equals title.AuthorId
            into titles
            where titles.Count() != 0
            select new { author.LastName, Count = titles.Count() };

可以在这里使用let来计算,我想:

var query = from author in authors
            join title in titleAuthor on author.AuthorId equals title.AuthorId
            into titles
            let count = titles.Count()
            where count != 0
            select new { author.LastName, Count = count };

或者您可以使用原始查询的更直接的翻译:

var innerQuery = from title in titleAuthor
                 group title by title.AuthorId into titles
                 select new { AuthorId = titles.Key, Count = titles.Count() };
var query = from author in authors
            join titleCount in innerQuery
              on author.AuthorId equals titleCount.AuthorId
            select new { author.AuthorId, titleCount.Count };