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



我有一个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 + ")";
}

如何将其转换为选择前三名结果?

您可以使用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);

相关内容

  • 没有找到相关文章

最新更新