Copied to clipboard

Flag this post as spam?

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


  • Levente Kosa 136 posts 352 karma points
    Jun 06, 2016 @ 16:18
    Levente Kosa
    0

    Foreach show every 12th, 24th, 36st etc elements

    Hi,

    I have problem to grab some element within a foreach. Basically I only want to see an element: - if first, or 12th, or 24th, or 36th etc and - if 11th, 23rd, 35th etc

    I have a hardcoded version, but obviously wrong this way

    @foreach (var item in items)
    {
        if (item.IsFirst() || item.IsPosition(12) || item.IsPosition(24) || item.IsPosition(36) || item.IsPosition(48))
        {
            show this one
        }
    
        if (item.IsPosition(11) || item.IsPosition(23) || item.IsPosition(35) || item.IsPosition(47))
        {
            show this one too
        }
    }
    

    Does anybody can help me with it?

  • Nicholas Westby 2054 posts 7100 karma points c-trib
    Jun 06, 2016 @ 17:19
    Nicholas Westby
    2

    Sounds like you just want every 12th item and every 12th item minus one:

    var items = new List<string>();
    for (var i = 0; i < items.Count; i++)
    {
        var twelfth = i % 12 == 0;
        var minusOne = (i - 1) % 12 == 0 && i > 1;
        if (twelfth || minusOne)
        {
            var item = items[i];
            //TODO: Something.
        }
    }
    

    The percent sign is the mod operator. Alternatively, you could construct your for loop to increment by 12 rather than increment by 1 and you'd have similar results.

  • Levente Kosa 136 posts 352 karma points
    Jun 06, 2016 @ 22:10
    Levente Kosa
    0

    Thank you for your help. Unfortunately I noticed that my basic concept is wrong and can't fit into my idea. So I have a different question, maybe you can help with it. I would like to render 10 items , after skip 2 items, another 10, another 2 skip.

    Is that possible somehow?

  • Nicholas Westby 2054 posts 7100 karma points c-trib
    Jun 06, 2016 @ 22:15
    Nicholas Westby
    0

    You should be able to use almost the same code that I posted (with a few minor changes to the calculations).

Please Sign in or register to post replies

Write your reply to:

Draft