fork(1) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. static class Program
  6. {
  7. public static void Main(string[] args)
  8. {
  9. var list1 = new int?[] {1, 2, 3, 4, 5};
  10. var list2 = new int?[] {3, 4, 5, 6, 7};
  11. var list3 = new int?[] {6, 9, 9};
  12.  
  13. var lockstep = LockStepSequences(new[] {list1, list2, list3});
  14.  
  15. foreach (var step in lockstep)
  16. Console.WriteLine(string.Join("\t", step.Select(i => i.HasValue? i.Value.ToString() : "null").ToArray()));
  17. }
  18.  
  19. public static IEnumerable<IEnumerable<T>> LockStepSequences<T>(this IEnumerable<IEnumerable<T>> sequences)
  20. {
  21. var iters = sequences
  22. .Select((s, index) => new {index, enumerator = s.GetEnumerator()})
  23. .Where(it => it.enumerator.MoveNext())
  24. .ToArray();
  25.  
  26. try
  27. {
  28. for(var active = iters.ToList(); active.Any();)
  29. {
  30. T min = active.Min(it => it.enumerator.Current);
  31. var corresponding = active.Where(it => Equals(it.enumerator.Current, min));
  32.  
  33. yield return iters.Select((el, i) => corresponding.Any(it => it.index == i)
  34. ? el.enumerator.Current
  35. : default(T));
  36.  
  37. active = active.Except(corresponding.Where(it => !it.enumerator.MoveNext())).ToList();
  38. }
  39. }
  40. finally
  41. {
  42. foreach (var iter in iters) iter.enumerator.Dispose();
  43. }
  44. }
  45. }
  46.  
  47.  
Success #stdin #stdout 0.06s 37320KB
stdin
Standard input is empty
stdout
1	null	null
2	null	null
3	3	null
4	4	null
5	5	null
null	6	6
null	7	null
null	null	9
null	null	9