开发者

Linq2Entities Grouping And Counting

I have 2 simple entities

  1. Activity
  2. ActivityViews

Activity Views has 2 properties ActivityID and DateTime. This entity allows me to see everytime an Activity was accessed.

I now want to write a LinqToEntity query that returns a list of Activities in descending order of how many times they have been viewed.

So far I have come up with this

  var activities= ((from a in db.Activities
                    join av in db.ActivityViews on a.ID equals av.Activity.ID
                    group a by new { a } into g
                    select new { g, No = g.Count() }).OrderByDescending(x => x.No)).Select(x => x.g).ToList();

It kind of works but its returning a list of开发者_如何转开发 annonymous types and I want to get a back a list of activity types. I dont want to return the count of views just for it to be ordered by them.

Edit : I take that back what I have doesnt work at all, if there are now ActivityViews for an Activity nothing gets returned.


Basically when you group whatever you group by is the key, so if you just select the key you will get what you need.

Here would be a solution to it.

var activities= 
  (
    (
       from a in db.Activities
       join av in db.ActivityViews
         on a.ID equals av.Activity.ID
       group a by a  into g
       select new { 
          a = g.Key, 
          No = g.Count() }
       ).OrderByDescending(x => x.No)
  ).Select(x => x.a)
  .ToList();

Working on simplifying this now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜