Copied to clipboard

Flag this post as spam?

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

  • Donovan Izilein 4 posts 84 karma points
    Dec 14, 2018 @ 13:05
    Donovan Izilein

    How to randomise and limit the number of items in a foreach loop

    Hi all,

    Please forgive my ignorance as I am very new to Umbraco (3 months) and I am still learning C#.

    I have created a Partial View Macro to display items on the front end of my site however I do not know how to get a random item from the foreach loop whilst also limiting it to 1 item.

    I have attached my Partial View Macro File code for you to view below.

    @inherits Umbraco.Web.Macros.PartialViewMacroPage
        var selection = Model.Content.Site().FirstChild("sermons").Children()
                            .Where(x => x.IsVisible())
        @foreach(var item in selection.Random(1)){
            <!-- Sermon Series -->
            <section class="container-fluid clearfix" id="MediaSeries" style="background-color: #@Umbraco.Field(item, "featuredSermonBackgroundColour");">
                <div class="container MediaSeriesBg">
                    <div class="row justify-content-center">
                        <div class="col-sm-12 order-2 order-sm-1 col-md-4 mb-5 mb-sm-0 text-light SermonTitle p-sm-2 p-md-3 p-lg-5">
                            <div class="mt-xl-5"> <span class="title">Sermon Series</span>
                                <h3><a href="@Umbraco.Field(item, "featuredSermonButtonURL")" class="text-white">@Umbraco.Field(item, "featuredSermonTitle")</a></h3>
                                <p>@Umbraco.Field(item, "featuredSermonIntroText")</p>
                                <span class="CTA"><a href="@Umbraco.Field(item, "featuredSermonButtonURL")" class="text-white">@Umbraco.Field(item, "featuredSermonButtonText")</a></span> 
                        <div class="col-sm-12 order-1 order-sm-2 col-md-8">
                            <a href="@item.Url"> 
                                <img src="@Umbraco.Field(item, "featuredSermonImage")" alt="@Umbraco.Field(item, "featuredSermonImageAltText") Teaching Series" class="img-fluid"/>  
                    </div><!-- row -->
                </div><!-- container -->
            </section><!-- Media Series Section -->



  • Alex Skrypnyk 5221 posts 19029 karma points MVP 3x admin c-trib
    Dec 16, 2018 @ 00:28
    Alex Skrypnyk

    Hi Don

    Try this code:

    @foreach(var item in selection.OrderBy(x => Guid.NewGuid()).FirstOrDefault())

    You can get random item with this code -

    list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()

    And you don't need a loop then.


  • Donovan Izilein 4 posts 84 karma points
    Dec 16, 2018 @ 13:26
    Donovan Izilein

    Thanks you for your help. Really appreciate it.

Please Sign in or register to post replies

Write your reply to: