Zip N IEnumerables together? Iterate over them simultaneously?

前端 未结 6 1572
春和景丽
春和景丽 2020-12-06 18:57

I have:-

IEnumerable> items;

and I\'d like to create:-

IEnumerable> r         


        
6条回答
  •  抹茶落季
    2020-12-06 19:27

    Now lightly tested and with working disposal.

    public static class Extensions
    {
      public static IEnumerable> JaggedPivot(
        this IEnumerable> source)
      {
        List> originalEnumerators = source
          .Select(x => x.GetEnumerator())
          .ToList();
    
        try
        {
          List> enumerators = originalEnumerators
            .Where(x => x.MoveNext()).ToList();
    
          while (enumerators.Any())
          {
            List result = enumerators.Select(x => x.Current).ToList();
            yield return result;
            enumerators = enumerators.Where(x => x.MoveNext()).ToList();
          }
        }
        finally
        {
          originalEnumerators.ForEach(x => x.Dispose());
        }
      } 
    }
    
    public class TestExtensions
    {
      public void Test1()
      {
        IEnumerable> myInts = new List>()
        {
          Enumerable.Range(1, 20).ToList(),
          Enumerable.Range(21, 5).ToList(),
          Enumerable.Range(26, 15).ToList()
        };
    
        foreach(IEnumerable x in myInts.JaggedPivot().Take(10))
        {
          foreach(int i in x)
          {
            Console.Write("{0} ", i);
          }
          Console.WriteLine();
        }
      }
    }
    

提交回复
热议问题