Copied to clipboard

Flag this post as spam?

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


  • Paul Claridge 9 posts 109 karma points
    Aug 24, 2018 @ 09:15
    Paul Claridge
    0

    how to introduce counter and break into my foreach loop

    Newbie so please be patient!

    I have this code which works fine: @foreach(var post in CurrentPage.Children) {

                }
    

    However, I would like to limit the list of Children displayed to say 8, rather than display all.

    I have also added a property DisplayDate (texstring) to the child doc type, which is of the form "Aug 2018", which I would like to sort the children on.

    I have tried adding a counter, but whatever I do to break out of the foreach loop has failed so far. I have also tried using an indexed list and for loop without success too. I also tried adding all sorts of OrderBy clauses to my list and that failed too. I really am mega frustrated! Could someone enlighten me please or at least say it cannot be done!

    Thanks, Paul

  • Jonny Flanagan 34 posts 163 karma points
    Aug 24, 2018 @ 11:08
    Jonny Flanagan
    0

    Hi Paul, I don't think you really need a counter. You could just order your posts in ascending or descending, then "take" the first 8 for example. Something like this might work for you.

    @foreach (var post in CurrentPage.Children.OrderByDescending(x => x.GetPropertyValue<DateTime>("articleDate")).Take(8)) {
    @post.displayDate
    @post.Name }
    
  • Paul Claridge 9 posts 109 karma points
    Aug 24, 2018 @ 12:03
    Paul Claridge
    100

    Thanks very much for responding - your timing is immaculate as I have just got something to work.

    I had to change my custom property to be a "date picker" (and then ToString("dd MMM yyy") to get my html), and also was getting super confused with the use (or lack of) the magical @! Sorry to have wasted your time - life is a learning experience .....

            @{ var count = 1; }
            @foreach(var post in CurrentPage.Children.OrderBy("displaydate descending"))
                {
                    <div class="col-sm-6">
                        <div class="content equal">
                            <a href="@post.Url">
                                <div class="date">@post.displayDate.ToString("dd MMM yyyy")</div>
                                    <h2>@post.Name</h2>     
                                <p>@Umbraco.Truncate(post.Introduction, 240, true)</p>
                            </a>
                        </div>
                    </div>
                    if(count++>9) {
                        break;
                    }
                }
    
Please Sign in or register to post replies

Write your reply to:

Draft