Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • kerrie 27 posts 67 karma points
    Jul 18, 2012 @ 17:46
    kerrie
    0

    unique tag values

    I am wanting to display a unique list of tags which can be placed on muliple nodes for a given document type.

     

    Here is what I have so far...

    @{

      var allNodesWithTags = @Model.Clients.Where("clientTags != \"\"");
                                            
    }
                                        
       @foreach (var item in allNodesWithTags)
        {
     
             string[] tags = @item.clientTags.ToString().Split(',');

                foreach(var t in tags)
               {
                
                 <a href="?tag=@t">@t</a><br />
              
                }

    }
        

     

    but how can I get a unique list of these tag values?  Currently it will get all the tags within the nodes for that doc type, so if  a tag has been used on two nodes for example it will show that tag name twice, which I dont want. I just want unique values.

    Thanks in advance!

  • Douglas Ludlow 210 posts 366 karma points
    Jul 18, 2012 @ 19:02
    Douglas Ludlow
    1

    You've got a few options, here are a couple I can think of off the top of my head. Not sure how efficient these are:

    Using a HashTable (only unique values are stored):

    @{
    var allNodesWithTags = Model.Clients.Where("clientTags != @0", "");

    HashSet<string> tags = new HashSet<string>();
    foreach (var node in allNodesWithTags)
    {
    foreach (string tag in node.clientTags.ToString().Split(','))
    {
    tags.Add(tag);
    }
    }

    foreach (string tag in tags)
    {
    <a href="?tag=@tag">@tag</a><br />
    }
    }

    Using LINQ's Distinct() method on a List:

    @{
    var allNodesWithTags = Model.Clients.Where("clientTags != @0", "");

    List<string> tags = new List<string>();
    foreach (var node in allNodesWithTags)
    {
    tags.AddRange(node.clientTags.ToString().Split(','));
    }

    foreach (string tag in tags.Distinct())
    {
    <a href="?tag=@tag">@tag</a><br />
    }
    }

     

  • kerrie 27 posts 67 karma points
    Jul 19, 2012 @ 10:32
    kerrie
    0

    Absolute star, thank you, worked a treat!

Please Sign in or register to post replies

Write your reply to:

Draft