【问题标题】:Linq query needs to select 3 instead of 1Linq 查询需要选择 3 而不是 1
【发布时间】:2014-04-12 11:41:02
【问题描述】:

我有一个 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 个结果?

【问题讨论】:

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


【解决方案1】:

您可以使用 Take 方法选择“顶部”:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多