They way that you think about a problem makes a big difference to how you code a solution to it. There are a number of ways to consider this problem and each one leads to a different solution... and different problems. When the solution you have come up with doesn't work it sometimes makes sense to start over with a different way of thinking about the problem.
The solution you have at the moment is essentially:
- Go through the list item by item
- After every third item:
- print group header
- print the items
The issue, as you've discovered, is that you never print the 3rd set of items because it only has 2 items in it. That 'after every third item' is why. If your list isn't an integer multiple of the set size then you never display the final set.
You can either change your way of thinking or just add an additional condition in there. Instead of just "after every third item" you could also add a check to see if you've reached the end of the list. That way on the last item you output the partial set.
Here are a couple of other ways to approach the problem:
- Print a header. Display 3 items. Repeat until you run out of items.
- Count up by 3, display the available items in the range
- Work from an array (or Enumerable), split it into appropriately-sized groups and work on the groups.
Each of these has issues that you'll have to solve.
There are any number of other ways to think about the problem, each with their own resulting solutions.
Just for the hell of it I threw together a silly, generalized LINQ solution to the third method. This is a suggestion, it's just an example of the kind of thing you can come up with when you try looking at a problem from a different angle.
void PrintCarousel<T>(IEnumerable<T> source, Action<T> printer)
{
var groups = source.Select((item, index) => (item, index)).GroupBy(r => r.index / 3, r => r.item);
foreach (var group in groups)
{
Console.WriteLine("Carousel Item");
foreach (var item in group)
printer(item);
}
}
And using it to print your 8 numbers:
PrintCarousel(Enumerable.Range(0, 8), i => Console.WriteLine($"Carousel Card : {i}"));
It's a dumb solution to this problem for several reasons. It' needlessly complex for what you're doing, it's expensive in terms of memory and code, it is generic without ever needing to be... and it's more than a little ugly.
Works though.