开发者

Finding n-Most Popular Using Linq

How should I structure a Linq query to return a List or Ienumerable of the most popular Tags in my db (I am using EF4.1 by the way).

Currently I have:

  var tagsListing = db.Tags
                            .GroupBy(q => q.Name)
                                .OrderByDescending(gp => gp.Cou开发者_如何学Pythonnt())
                                .Take(5)
                                .Select();

I think I am part of the way there, but I am unsure of how to structure the Select statement...


Your Select call could look like this:

.Select(gp => gp.Key)

That will give you an IEnumerable<string> of your most popular tags (assuming that Name is a string).


Assuming you want the name and the count, just:

.Select(g => new { Name = g.Key, Count = g.Count() });

EDIT: If you want the complete tags as well, you could use:

.Select(g => new { Tags = g, Count = g.Count() })

which would give you a sequence of groups of tags, all with the same name within a group. Or you might only want the first tag within each group, e.g.

.Select(g => g.First())

It's not clear what a Tag consists of, or what exactly you want in the results.


You've written a perfectly workable query and do not need to call .Select

IQueryable<IGrouping<string, Tag>> tagsListing = db.Tags
  .GroupBy(q => q.Name)
  .OrderByDescending(gp => gp.Count())
  .Take(5);

List<IGrouping<string, Tag>> results = tagListing.ToList();


You probably want to select the names like this:

.Select(gp => gp.Key);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜