Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Returns a new sequence that contains elements from the first sequence interleaved with elements from the second sequence.
- /// </summary>
- /// <typeparam name="T">The type of elements in the input sequences.</typeparam>
- /// <param name="first">The first input sequence.</param>
- /// <param name="second">The second input sequence.</param>
- /// <returns>A new sequence that contains elements from the first sequence interleaved with elements from the second sequence.</returns>
- public static IEnumerable<T> InterleaveWith<T>(this IEnumerable<T> first, IEnumerable<T> second)
- {
- return first.InterleaveWith(second, 1, 1);
- }
- /// <summary>
- /// Returns a new sequence that contains groups of elements from the first sequence
- /// interleaved with groups of elements from the second sequence.
- /// </summary>
- /// <typeparam name="T">The type of elements in the input sequences.</typeparam>
- /// <param name="first">The first input sequence.</param>
- /// <param name="second">The second input sequence.</param>
- /// <param name="firstSequenceGroupSize">The consecutive number of items in groups of items from the first sequence.</param>
- /// <param name="secondSequenceGroupSize">The consecutive number of items in groups of items from the second sequence.</param>
- /// <returns>A new sequence that contains groups of elements from the first sequence interleaved with groups of elements from the second sequence.</returns>
- public static IEnumerable<T> InterleaveWith<T>(this IEnumerable<T> first, IEnumerable<T> second, int firstSequenceGroupSize, int secondSequenceGroupSize)
- {
- using (var firstIterator = first.GetEnumerator())
- using (var secondIterator = second.GetEnumerator())
- {
- var exhaustedFirst = false;
- // Keep going while we've got elements in the first sequence.
- while (!exhaustedFirst)
- {
- for (var i = 0; i < firstSequenceGroupSize; i++) {
- if (!firstIterator.MoveNext()) {
- exhaustedFirst = true;
- break;
- }
- yield return firstIterator.Current;
- }
- // This may not yield any results - the first sequence
- // could go on for much longer than the second. It does no
- // harm though; we can keep calling MoveNext() as often
- // as we want.
- for (var i = 0; i < secondSequenceGroupSize; i++)
- {
- // This is a bit ugly, but it works...
- if (!secondIterator.MoveNext()) {
- break;
- }
- yield return secondIterator.Current;
- }
- }
- // We may have elements in the second sequence left over.
- // Yield them all now.
- while (secondIterator.MoveNext()) {
- yield return secondIterator.Current;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment