Copied to clipboard

Flag this post as spam?

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


  • Rasmus Fjord 659 posts 1546 karma points c-trib
    Feb 17, 2012 @ 11:20
    Rasmus Fjord
    0

    razor syntax question on converting a collection of 1 item

    Hey :)

    Im doin' my first razor only site, so i want to get everything top notch :)

    I have a collection of newsItems, from this collection I need to latest one on the stack and display it abit more in detail. So what I did so far is

    @{
      @*First we need the list of news*@
       var listOfNews = @Model.news.OrderBy("newsPubDate desc");
      
      @*Get latest news to be used for top news*@
       var latestNews = @listOfNews.Take(1);
      }

    So at the moment "latestNews" is a collection of 1 newsItem.

    How do i cast/convert it into just a newsItem, so i can get the data out ?

    I know i can just do a foreach on the one item and it would work but find it a bit silly to do it like that. :)

  • Douglas Ludlow 210 posts 366 karma points
    Feb 17, 2012 @ 12:31
    Douglas Ludlow
    1

    You have to remember that razor is essentialy c#. The easiest way I can think of is as follows:

    @{
    //
    First we need the list of news
    var listOfNews = Model.news.OrderBy("newsPubDate desc");
     
    //Get latest news to be used for top news
     var latestNews = listOfNews.First();
    }
  • Rasmus Fjord 659 posts 1546 karma points c-trib
    Feb 17, 2012 @ 12:36
    Rasmus Fjord
    0

    your right just keep forgettin' it because there is some things done differently because of the razor but it could just be done like in C#.

    It will properbly stick after im finished with this solution :)

     Which means i just can do like this -.- DOH

    @listOfNews[0];
  • Douglas Ludlow 210 posts 366 karma points
    Feb 17, 2012 @ 12:53
    Douglas Ludlow
    0

    Yup, there you go, even easier!

  • 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