How to use Linq to Group By individual items in a Collection?
I'm trying to find the most popular Tags
that are used for a BlogPost
.
eg.
public class BlogPost
{
public int Id { get; set; }
public IEnumerable<string> Tags { get; set; }
}
So I tried:
var tags = (from p in BlogPosts()
group bp by bp.Tags into g
select new {Tag = g.Key, Count = g.Count()})
.OrderByDescending(o => o.Count)
.Take(number);
but this doesn't compile. Error is:
Cannot 开发者_运维问答implicitly convert type 'System.Linq.IQueryable<{Tag: System.IEnumerable<string>, Count: int}>' to 'System.Collections.Generic.Dictionary<string, int>'.
See how it's a list of strings? I was hoping to look through each tag in every blog post, and count the most popular ones.
I don't think you can group on a IEnumerable<string>
, try this:
var tags = (from t in BlogPosts.SelectMany(p => p.Tags)
group t by t into g
select new {Tag = g.Key, Count = g.Count()})
.OrderByDescending(o => o.Count)
.Take(number);
SelectMany is the key here.
var tags = posts
.SelectMany (p => p.Tags)
.GroupBy (t => t).Select(t => new {Tag = t.First (), Count=t.Count ()})
.OrderBy(tc => tc.Count)
.Select(tc => tc.Tag)
.Take (15);
You want to group on singular tag names, not on whole lists of tags, which is what you are currently doing. Try this:
var tags =
(from p in posts
from tag in p.Tags
group tag by tag into g
select new {Tag = g.Key, Count = g.Count()})
.OrderByDescending(o => o.Count)
.Take(number);
Though this should do what you are asking for, it won't fix the compile error you're getting. That's somewhere else.
精彩评论