Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C#

Idiom #163 Print list elements by group of 2

Print all the list elements, two by two, assuming list length is even.

using System.Collections.Generic;
for(int i = 0; i < list.Count; i += 2) {
  Console.WriteLine(string.Format("{0}, {1}", list[i], list[i + 1]));
}
using System;
using System.Linq;
foreach (var chunk in list.Chunk(2))
{
    Console.WriteLine(string.Join(' ', chunk));
}

.NET 6 preview 7 adds a chunk function to LINQ.

list is IEnumerable<T>; chunk is T[].
#include <stdio.h>
for (unsigned i = 0; i < sizeof(list) / sizeof(list[0]); i += 2)
	printf("%d, %d\n", list[i], list[i + 1]);

I'm treating list as an array not a list because C doesn't have lists built in.
The length had better be even or there'll be undefined behaviour to pay!

New implementation...