Create a tag cloud with a limited amount of tags in ASP.NET and LINQ
Today I built a Tag cloud for my new site. I found this great article about how to do it with LINQ and C#. But I missed some features. Especially how to limit the number of tags that were shown. So if you read that article and then have a look at this code if you have the same problem as me.
var tagSummary = (from ti in db.TagItemRelations group ti by ti.Tag.Text into tagGroup select new { Tag = tagGroup.Key, TagFrequency = tagGroup.Count() }).OrderByDescending(x=>x.TagFrequency).Take(20); int maxTagFrequency = (from t in tagSummary select t.TagFrequency).Max(); var tagCloud = (from ti in tagSummary select new TagCloudItem { Tag = ti.Tag, Weight = (double)ti.TagFrequency / maxTagFrequency * 100 }).OrderBy(x=>x.Tag);
The main difference between my code and the code in the article is that I have a slightly more complex data model (should not matter) and that I make the second query against the “result” from the first query. This allows me to first order by popularity and then in alphabetic order.
Please leave a comment if there is any better way to do this or if you have any questions.