I have list of items, for example: { i1, i2, i3, i4, i5, i6, i7 }.
I want to get a list, where every item is a pair of items from source list: { {i1, i2}, {i3, i4}, {i5, i6}, {i7} }.
i7 is a single item in pair because there is no item i8.
Is it possible to do with LINQ?
I have list of items, for example: { i1, i2, i3, i4, i5, i6,
Share
Well, you could do:
The result is an
IGrouping<int, T>with a key of 0, 1, 2 etc and the contents of each group being one or two items.However, I’d possibly write a custom extension method:
This will yield a sequence of tuples – the downside here is that the final tuple will have the default value for
Tas the “second” item if the sequence has an odd number of items. For reference types where the sequence only consists of non-null values, that’s okay, but for some sequences it wouldn’t help.