2

I have an IEnumerable of Video objects as my Razor View's Model.

@model IEnumerable<VideoViewModel>

I am trying to make it so every 2 videos will be inside of a bootstrap row. The first video of the two will be in the first col-md-6 and the second video of the two will be in the second col-md-6.

Here is an example of what I am looking to do with a razor foreach loop:

<div class="row">
    <div class="col-md-6">
        First video in model
    </div>
    <div class="col-md-6">
        Second video in model
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        Third video in model
    </div>
    <div class="col-md-6">
        Fourth video in model
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        Fifth video in model
    </div>
    <div class="col-md-6">
        Sixth video in model
    </div>
</div>
Blake Rivell
  • 13,105
  • 31
  • 115
  • 231
  • There is no need for a linq extension method. You can do this simply in the view using a `for` loop and a modulus operator `if (i % 2 == 0)` to start a new `
    `
    –  Oct 12 '16 at 22:21

1 Answers1

4

You need to batch your list and then loop through the batches. You can create an extension method like this (from Create batches in linq):

public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(
                  this IEnumerable<TSource> source, int size)
{
    TSource[] bucket = null;
    var count = 0;

    foreach (var item in source)
    {
        if (bucket == null)
            bucket = new TSource[size];

        bucket[count++] = item;
        if (count != size)
            continue;

        yield return bucket;

        bucket = null;
        count = 0;
    }

    if (bucket != null && count > 0)
        yield return bucket.Take(count);
}

Then you can run through the batches like this:

@foreach(var batch in Model.Batch(2))
{
    <div class="row">
    @foreach(var item in batch)
    {
        <div class="col-md-6">
            Fifth video in model
        </div>

    }
    </div>
}
Community
  • 1
  • 1
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • This is a neater function for doing the batching: http://stackoverflow.com/a/6362642/249879 – Marc O'Morain Oct 12 '16 at 16:59
  • Looks neater, but is not as efficient as the above. – Kenneth Oct 12 '16 at 17:10
  • @Kenneth Thank you very much for this answer. I just created a static class called LinqExtensions and added the extension method you gave. Then in my razor the code you supplied worked perfectly. It is ashame I am not able to install moreLinq in an asp.net core project. I never know where I should be placing an extension method class in an asp.net mvc project so I just threw it in my Core/Models folder... – Blake Rivell Oct 12 '16 at 18:57