How to “zip” or “rotate” a variable number of lists?

后端 未结 8 1657
广开言路
广开言路 2020-11-27 20:47

If I have a list containing an arbitrary number of lists, like so:

var myList = new List>()
{
    new List() { \"a\",          


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 21:10

    You can roll your own ZipMany instance which manually iterates each of the enumerations. This will likely perform better on larger sequences than those using GroupBy after projecting each sequence:

    public static IEnumerable ZipMany(
        IEnumerable> source,
        Func, TResult> selector)
    {
       // ToList is necessary to avoid deferred execution
       var enumerators = source.Select(seq => seq.GetEnumerator()).ToList();
       try
       {
         while (true)
         {
           foreach (var e in enumerators)
           {
               bool b = e.MoveNext();
               if (!b) yield break;
           }
           // Again, ToList (or ToArray) is necessary to avoid deferred execution
           yield return selector(enumerators.Select(e => e.Current).ToList());
         }
       }
       finally
       {
           foreach (var e in enumerators) 
             e.Dispose();
       }
    }
    

提交回复
热议问题