Umbraco Razor c# Listing unique tags

1.4k views Asked by At

I have been trying to create a blog using Umbraco v6 using Razor.

This is my first Umbraco project so I am still getting to grips with things but I have managed to get most of it working how I want but I would like to list tags in a side widget.

So far I have this -

@{
    var blogitems = Umbraco.Content("1188").Children.Where("Visible");

    foreach(var blog in blogitems) {
        var tagsplit = blog.tags.Split(',');
        foreach(var tag in tagsplit) {
                <li>                    
                        <a href="/blog/?@tag">@tag</a>
                </li>
        }
    }
}

The problem is this lists all tags duplicating many of them. I have tried to use .Distinct on the tagsplit variable which just returns an error.

Any ideas?

2

There are 2 answers

0
Kaizen Programmer On

.Distinct() should work, but since it's not, a quick and dirty solution is:

@{
    var blogitems = Umbraco.Content("1188").Children.Where("Visible");

    foreach(var blog in blogitems) {
        var tagsplit = blog.tags.Split(',');
        var usedTags=new List<string>();
        foreach(var tag in tagsplit) {
            if(!usedTags.Contains(tag)){
                <li>                    
                        <a href="/blog/?@tag">@tag</a>
                </li>
            }
            usedTags.Add(tag);
        }
    }
}
0
Sam On

To get all tags in Umbraco:

Umbraco.TagQuery.GetAllContentTags().OrderBy(t => t.Text)

The reason your query is giving you duplicates is because your blog items have the same tags on them and you are duplicating in the wrong place.

var tagList = Umbraco.Content(1188).Children
    .Where("Visible")
    .SelectMany( c => c.tags.Split(',') )
    .Distinct()
    .OrderBy( x => x )

will give you a nice, ordered list of all the tags from all your content...