Linq查询需要选择3而不是1

时间:2014-04-12 11:41:03

标签: .net linq asp.net-mvc-4 linq-to-entities

我有一个只使用Entity Framework选择最高结果的linq查询。

 var countOfArticlesPerCity = db.ArticleViews
       .GroupBy(s => new { s.ArticleID, s.ActualCity })
       .Select(g => new { g.Key.ArticleID, g.Key.ActualCity, Count = g.Count() });

var highestArticleCountPerCity = countOfArticlesPerCity
       .GroupBy(x => x.ActualCity)
       .Select(g => g.OrderByDescending(x => x.Count)
       .FirstOrDefault());

var highestArticleCountPerCityWithArticleTitle = db.Articles
       .Join(highestArticleCountPerCity, x => x.ID, p => p.ArticleID, (x, p) => new { x.title, p.ActualCity, p.Count });

foreach (var line in highestArticleCountPerCityWithArticleTitle)
{
     ViewBag.viewedByCity = line.title + ", " + line.ActualCity + " (" + line.Count + ")";
}

我如何将其转换为选择前3个结果?

1 个答案:

答案 0 :(得分:1)

您可以使用Take方法选择'Top':

 var highestArticleCountPerCityWithArticleTitle = db.Articles
           .Join(highestArticleCountPerCity, x => x.ID, p => p.ArticleID, (x, p) => new { x.title, p.ActualCity, p.Count })
           .Take(3);