Group elements in pairs

I have a list of elements, for example: { i1, i2, i3, i4, i5, i6, i7 } .
I want to get a list where each element is a pair of elements from the original list: { {i1, i2}, {i3, i4}, {i5, i6}, {i7} } .
i7 is a single element in a pair because there is no i8 element.
Is this possible with LINQ?

+7
source share
1 answer

Well, you could do:

 var pairs = sequence.Select((value, index) => new { value, index } ) .GroupBy(x => x.index / 2, x => x.value) 

The result is IGrouping<int, T> with the key 0, 1, 2, etc., and the contents of each group are one or two elements.

However, I could write my own extension method:

 public static IEnumerable<Tuple<T, T>> PairUp<T>(this IEnumerable<T> source) { using (var iterator = source.GetEnumerator()) { while (iterator.MoveNext()) { var first = iterator.Current; var second = iterator.MoveNext() ? iterator.Current : default(T); yield return Tuple.Create(first, second); } } } 

This will give a sequence of tuples. The disadvantage here is that the final tuple will have a default value for T as the "second" element if the sequence has an odd number of elements. For reference types, where the sequence consists only of non-zero values, this is normal, but for some sequences this did not help.

+11
source

All Articles