Copied to clipboard

Flag this post as spam?

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


  • Søren Mastrup 122 posts 564 karma points c-trib
    Feb 26, 2016 @ 08:45
    Søren Mastrup
    0

    Check if a uTaxonomy property contains a string

    I have a node with a uTaxonomy property. When accessing my property I get this: "System.Collections.Generic.List`1[ASP.Taxonomy]".

    When looping the Generic.List I get all the names of the taxonomies:

    foreach(var item in employee.departments){
        @item
    }
    

    How can I, in this foreach, check if the list contains for example "accounting"?

    I have tried using employee.departments.Contains("accounting"), but I am getting this:

    The best overloaded method match for 'System.Collections.Generic.List<ASP.Taxonomy>.Contains(ASP.Taxonomy)' has some invalid arguments
    
  • Delete 61 posts 450 karma points
    Feb 26, 2016 @ 09:55
    Delete
    100

    Hi Søren,

    I think you have a problem, because when you are trying to call the Contains method, departments property is a dynamic type.

    Try this:

    @(((string)item.ToString()).Contains("accounting"))
    

    I hope I understood you correctly.

    I'll add another method that will return (true/false), if the required value is in the collection or not

    Vitaly

  • Søren Mastrup 122 posts 564 karma points c-trib
    Feb 26, 2016 @ 10:52
    Søren Mastrup
    0

    Hi Vitaly

    Thanks! I got it to work by doing this:

        bool showEmployee = false;
        foreach(var item in employee.departments){
            if((((string)item.ToString().ToLower()).Contains(kategori))){
                showEmployee = true;
            }
        }
        if(showEmployee){
            <div>Employee data</div>
        }
    

    It's not pretty, but it solves my problem :-)

  • Delete 61 posts 450 karma points
    Feb 26, 2016 @ 12:24
    Delete
    0

    Hi Søren,

    You can try to add below method in TaxonomyExtensions class in Taxonomy.cs which is located in the App_Code folder.

    public static bool HasValue(this IEnumerable<Taxonomy> values, string value)
        {
            return values.Any(x => x.Item.Name == value);
        }
    

    How to use:

    @{ var taxonomy = Model.Content.GetPropertyValue<List<Taxonomy>>("yourPropertyName"); }
    
    @if(taxonomy.HasValue("accounting")){ // first code } else { // second code } 
    

    Best regards, Vitaly

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies