How to use Zip on three IEnumerables [duplicate]

纵饮孤独 提交于 2021-01-27 04:13:43

问题


Possible Duplicate:
Create Items from 3 collections using Linq

I have performed a zippage of two sequences as follows.

IEnumerable<Wazoo> zipped = arr1.Zip(arr2, (outer, inner) =>
  new Wazoo{P1 = outer, P2 = inner});

Now, I just realized that I'll be using three sequences, not two. So I tried to redesign the code to something like this:

IEnumerable<Wazoo> zipped = arr1.Zip(arr2, arr3, (e1, e2, e3) =>
  new Wazoo{P1 = e1, P2 = e2, P3 = e3});

Of course, it didn't work. Is there a way to deploy Zip to incorporate what I'm aiming for? Is there an other method for such usage? Will I have to zip two of the sequences and then zip them with the third unzipping them in the process?

At this point I'm about to create a simple for-loop and yield return the requested structure. Should I? I'm on .Net 4.


回答1:


You could either use two calls to the existing Zip (it would be a bit messy, but it would work) or you could just make your own Zip that takes 3 sequences.

public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>
    (this IEnumerable<TFirst> source, IEnumerable<TSecond> second
    , IEnumerable<TThird> third
    , Func<TFirst, TSecond, TThird, TResult> selector)
{
    using(IEnumerator<TFirst> iterator1 = source.GetEnumerator())
    using(IEnumerator<TSecond> iterator2 = second.GetEnumerator())
    using (IEnumerator<TThird> iterator3 = third.GetEnumerator())
    {
        while (iterator1.MoveNext() && iterator2.MoveNext()
            && iterator3.MoveNext())
        {
            yield return selector(iterator1.Current, iterator2.Current,
                iterator3.Current);
        }
    }
}


来源:https://stackoverflow.com/questions/12640881/how-to-use-zip-on-three-ienumerables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!