Copied to clipboard

Flag this post as spam?

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


  • Jonas 10 posts 30 karma points
    Jan 26, 2010 @ 00:54
    Jonas
    0

    Sort content by property programmatically

    Hey guys.

    Do you know how to sort content in c#? I use

    Content[] eventsRaw = Content.getContentOfContentType(contentType);

    And I want to sort this array by a property called "Date". I am still new to Umbraco, and usually I just make a lambda expression in LinQ, but unfortunately this is not possible with the Umbraco datatypes.

    Appreciate some suggestions.

  • Sebastiaan Janssen 5058 posts 15520 karma points MVP admin hq
    Jan 26, 2010 @ 09:16
    Sebastiaan Janssen
    0

    If you're trying to sort content in the backend, this would be a start. Next you could do a for-each on eventsRaw and evaluate the property you needs (event.getProperty("myProperty")), this can easily be done with a linq query.

    However, I suppose you're trying to do this in the frontend, in which you really don't want to do this using the content class as it pulls directly from the database. If you must do this in code then search around a bit for the XPathNodeIterator. But easier than that, just use an XSLT for your presentation. You can get all of the nodes you need and do an xls-sort on them. 

  • Jonas 10 posts 30 karma points
    Jan 26, 2010 @ 10:12
    Jonas
    0

    Thanks for the answer. But I have already tried evaluating the  (event.getProperty("myProperty")) in a linq query, but this results in an exception about IComparable. 

    I'll take a look at the XPathNodeIterator. I guess this is an XML representation of all content of some sort? 

    If everything fails, I will do an XSLT representation. I just not a big fan of its syntax :)

  • Thomas Höhler 1237 posts 1709 karma points MVP
    Jan 26, 2010 @ 10:18
    Thomas Höhler
    1

    You can use something like this:

    public void xy()
    {
    Content[] eventsRaw = Content.getContentOfContentType(new ContentType(1));
    var newEventList = new List<Content>();
    newEventList.AddRange(eventsRaw);
    newEventList.Sort(CompareContentByXy);
    }

    public static int CompareContentByXy(Content x, Content y)
    {
    var val1 = (string)x.getProperty("YOURPROPERTY").Value;
    var val2 = (string)y.getProperty("YOURPROPERTY").Value;
    return val1.CompareTo(val2);
    }

    For sure if the property is a date or an int just convert the props to the correct type.

    hth, Thomas

  • Sebastiaan Janssen 5058 posts 15520 karma points MVP admin hq
    Jan 26, 2010 @ 10:33
    Sebastiaan Janssen
    1

    @Jonas Yes, it's the XML that you'll be using.

    If your site is of any size, you should not be getting the content straight from the database, (by doing Content.getContent...), it's a massive performance hit.

Please Sign in or register to post replies

Write your reply to:

Draft