Copied to clipboard

Flag this post as spam?

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


  • Peter van Geffen 54 posts 290 karma points
    May 02, 2023 @ 17:44
    Peter van Geffen
    0

    How to split a foreach loop in groups of four items?

    How can i split a foreach in groups of (max.) four? It is a list from a nested content

    • Item 01
    • Item 02
    • Item 03
    • Item 04

    • Item 05
    • Item 06
    • Item 07
    • Item 08

    • Item 09
    • Item 10
  • Marc Goodson 2155 posts 14408 karma points MVP 9x c-trib
    May 02, 2023 @ 20:36
    Marc Goodson
    1

    Hi Peter

    I wonder if you can make use of the InGroupsOf extension method that Umbraco has in the Umbraco.Extensions namespace...

    https://github.com/umbraco/Umbraco-CMS/blob/7df5c9c212185bf50f27aa348e3c3698cc97af57/src/Umbraco.Core/Extensions/EnumerableExtensions.cs#L41

    So you can do

        @foreach(var group in Model.YourNestedContentProperty.InGroupsOf(4)) {  
             <div class="grouping">         
                  @foreach (var item in group) {
                       <div class="grouped-item">@item.Name</div>
                   }
              </div>
         }
    

    Regards

    Marc

  • Peter van Geffen 54 posts 290 karma points
    May 03, 2023 @ 04:35
    Peter van Geffen
    100

    Thanks for your reaction, but it was a bit to technical for me. I asked ChatGPT the same question and it came up with this:

    var items = Model.Value<IEnumerable<IPublishedElement>>("partners");
    if (items != null) {
        var setsOfFour = items.Chunk(4);
        foreach (var set in setsOfFour){
            <div class="set-of-four">
                @foreach (var item in set){
                    <p>@item.Name</p>
                }
            </div>
        }
    }
    

    It worked for me.

  • Marc Goodson 2155 posts 14408 karma points MVP 9x c-trib
    May 03, 2023 @ 07:56
    Marc Goodson
    0

    Hi Peter

    No problem, sorry I wasn't clearer!, glad you got it working!

    Basically, InGroupsOf is an extension method provided by Umbraco to help people do what you have done without having to know about things like 'chunk'!

    so your example above would be:

    var items = Model.Value<IEnumerable<IPublishedElement>>("partners");
    if (items != null) {
        foreach (var set in items.InGroupsOf(4)){
            <div class="set-of-four">
                @foreach (var item in set){
                    <p>@item.Name</p>
                }
            </div>
        }
    }
    

    It's just meant to provide a sugary syntax that is more descriptive about what is going on, but if you are familiar with the raw Linq method, then it's completely fine to do it that way!

    regards

    Marc

Please Sign in or register to post replies

Write your reply to:

Draft