using System.Collections.Generic;
public static void Main()
Console.WriteLine("Building lists:");
PrintList(Interleave("ABC".ToCharArray().ToList(), "123".ToCharArray().ToList()));
PrintList(Interleave("ABCDE".ToCharArray().ToList(), "123".ToCharArray().ToList()));
PrintList(Interleave("ABC".ToCharArray().ToList(), "12345".ToCharArray().ToList()));
Console.WriteLine("Walking through enumerators:");
PrintList("ABC".ToCharArray().InterleaveWith("123".ToCharArray()));
PrintList("ABCDE".ToCharArray().InterleaveWith("123".ToCharArray()));
PrintList("ABC".ToCharArray().InterleaveWith("12345".ToCharArray()));
public static void PrintList<T>(IEnumerable<T> items)
Console.WriteLine(string.Join(",", items));
public static List<T> Interleave<T>(List<T> male, List<T> female)
var children = new List<T>();
var childrenCount = male.Count + female.Count;
for (int i = 0; i < childrenCount; i++)
if (indexMale < male.Count)
children.Add(male[indexMale]);
children.Add(female[indexFemale]);
if (indexFemale < female.Count)
children.Add(female[indexFemale]);
children.Add(male[indexMale]);
public static class IEnumerableExtensions
public static IEnumerable<T> InterleaveWith<T>(this IEnumerable<T> sequenceA, IEnumerable<T> sequenceB)
var enumA = sequenceA.GetEnumerator();
var enumB = sequenceB.GetEnumerator();
yield return enumA.Current;
yield return enumB.Current;
yield return enumB.Current;