Zip N IEnumerables together? Iterate over them simultaneously?

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

I have:-

IEnumerable> items;

and I\'d like to create:-

IEnumerable> r         


        
6条回答
  •  佛祖请我去吃肉
    2020-12-06 19:26

    Based on David B's answer, this code should perform better:

    public static IEnumerable> JaggedPivot(
        this IEnumerable> source)
    {
        var originalEnumerators = source.Select(x => x.GetEnumerator()).ToList();
        try
        {
            var enumerators =
                new List>(originalEnumerators.Where(x => x.MoveNext()));
    
            while (enumerators.Any())
            {
                yield return enumerators.Select(x => x.Current).ToList();
                enumerators.RemoveAll(x => !x.MoveNext());
            }
        }
        finally
        {
            originalEnumerators.ForEach(x => x.Dispose());
        }
    }
    

    The difference is that the enumerators variable isn't re-created all the time.

提交回复
热议问题