Home

Creating a Tag Cloud with c# and IEnumberable<>

I recently had to create a tag cloud for an application I’m writing. The tags are attached to bookmarks.

The function returns a paragraph tag with a link for each tag. Each link has a specific class attribute set depending on the weighting given to that tag.

The C# code:

public class TagCloudGenerator
    {
        public string MakeTagCloud(IQueryable<BookmarkTag> Tags)
        {
            Decimal totaltags = Tags.Count();
            Decimal tagpercent = 0;
            int tagweight = 0;

            StringBuilder TagCloud = new StringBuilder();

            var groupedtags = Tags.GroupBy(t => t.Tag);

            TagCloud.Append("

"); foreach (var tag in groupedtags) { tagpercent = (tag.Count() / totaltags) * 100; if (tagpercent >= 90) { tagweight = 1; } else if (tagpercent >= 70) { tagweight = 2; } else if (tagpercent >= 40) { tagweight = 3; } else if (tagpercent >= 20) { tagweight = 4; } else if (tagpercent >= 3) { tagweight = 5; } else { tagweight = 0; } TagCloud.Append(String.Format("{2} ", tag.Key.Replace(" ", "-"), tagweight, tag.Key)); } TagCloud.Append("

"
); return TagCloud.ToString(); } }

The CSS:

/* Tag Cloud */

.tagcloud
{
    text-align: left;
}

.tagcloud a
{
    padding: 0px 10px 0px 0px;
    text-decoration:none;
    padding:3px 4px;
    white-space:nowrap  
}

.tagcloud a:hover
{
    background-color:#fff;
    color:#012840;
}

.tagcloud .tag1
{
    font-size: 2em;
}

.tagcloud .tag2
{
    font-size: 1.7em;
}

.tagcloud .tag3
{
    font-size: 1.5em;
}

.tagcloud .tag4
{
    font-size: 1.2em;
}

.tagcloud .tag5
{
    font-size: 1em;
}

.tagcloud .tag0
{
    font-size: .8em;
}

Comments (3)

Simon

This saved me a lot of time.

Cheers

Simon

8 years ago
Doug Rathbone

Cool.. was going to write somthing almost identical and will be happily ripping this off :)

keep up the good work - you have a new subscriber :)

8 years ago
[Pingback]

<...> Las Vegas « Creating a Tag Cloud with c# and IEnumberable<> <...>

8 years ago


Comments are closed.