在ASP.Net MVC 4中使用Entity Framework,需要使用linq输出一行信息。
我有一个ArticleView表和一个Article表。我需要在24小时内输出活动最多的文章。
这是我的ArticleView表:
int ArticleID
DateTime ViewCreated
文章表:
int ID
string title
示例数据:
ArticleView:
ArticleID ViewCreated
2 4/8/2014 1:48:40 PM
2 4/8/2014 1:50:40 PM
2 4/8/2014 1:55:20 PM
3 4/8/2014 12:07:30 PM
注意:一旦有人查看文章,就会自动生成ViewCreated。
Article:
ID Title
2 Article2
3 Article3
预期输出:
24小时内活动最多的文章是:
第二条(3)
我必须与之合作:
var articles = db.Articles;
var articleviews = db.ArticleViews;
只是不确定如何处理这个问题。
答案 0 :(得分:2)
这样的事情:
var viewsById = db.ArticleViews
.Where(av => av.ViewCreated >= startDateTime && av.ViewCreated < endDateTime)
.GroupBy(av => av.ArticleId)
.Select(g => new { ArticleId = g.Key, Count = g.Count() })
var highestCount = viewsById.Max(v => v.Count);
var topArticles = viewsById.Where(a => a.Count == highestCount);
var topArticle = topArticles.First();
var message = String.Format("Article id: {0}, views: {1}",
topArticle.ArticleId, topArticle.Count);
答案 1 :(得分:0)
您可以通过使用连接来执行此操作:
var mostViewedArticleTitleAndCount = db.Articles
.Join(ArticleViews.Where (av => av.ViewCreated > sinceDate),
a => a.ID,
v => v.ArticleID,
(a,v) => new { a,v })
.GroupBy (g => g.a.ID)
.Select (g => new { g.Key, Title = g.First ().a.Title, Count = g.Count ()})
.OrderByDescending (g => g.Count)
.Select (g => g.Title + "(" + g.Count + ")")
.First ();
对于您的测试数据,这将输出:
第二条(3)
答案 2 :(得分:0)
要获得该文章,您可以简单地执行此操作:
var article = db.Articles.OrderByDescending(a=>a.ArticleViews.Count())
.Take(1).FirstOrDefault();
或者
var article = db.Articles.OrderByDescending(a=>a.ArticleViews.Count())
.FirstOrDefault()//this should work too
建议解决方案的一个简短方法是:
var mostViewedArticle = db.ArticleViews
.Where(av => av.ViewCreated >= startDateTime && av.ViewCreated < endDateTime)
.GroupBy(av => av.ArticleId)
.OrderByDescending(g=> g.Count())
.Select(g => g.First().Article)
.Take(1)
Article
至导航属性First
一个。