Create a tag cloud with limited amout of tags in ASP.NET and LINQ

Today i built a Tag cloud for my new site. I found this great article about on how to do it with LINQ and C#. But i missed some features. Especially how to limit the number of tags that was 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 slightly more complex data model (should not matter) and that i make the second query against the “result” from the first query. This allow 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.

One Comment

  1. Kosta says:

    Hey,

    Just wanted to let you know that I have updated the link above since I just migrated to wordpress.

    If anyone wants reference to the original article, you can find it here:

    http://kosta.apostolou.ca/software-development/how-to-create-a-tagcloud-using-linq-and-aspnet

    Thanks,
    Kosta

Leave a Reply