Reputation: 364
I have a collection of objects. I've made sure it has an even amount of objects.
Object1
Object2
Object3
Object4
Object5
Object6
I need to transform the collection to tuples, like this
Tuple(Object1, Object2),
Tuple(Object3, Object4),
Tuple(Object5, Object6)
I've been trying to come up with an extension method for it, but I haven't figured out anything.
public static IEnumerable<Tuple<T, T>> ToTuples(this IEnumerable<T> objects)
{
// what do I do here?
}
Upvotes: 0
Views: 81
Reputation: 36483
Something like this maybe?
public static IEnumerable<Tuple<T, T>> ToTuples<T>(this IEnumerable<T> objects)
{
IEnumerator<T> enumerator = objects.GetEnumerator();
while (enumerator.MoveNext())
{
T object1 = enumerator.Current;
if (enumerator.MoveNext())
{
yield return Tuple.Create(object1, enumerator.Current);
}
}
}
Upvotes: 2