如何在三个IEnumerables上使用Zip [英] How to use Zip on three IEnumerables

查看:42
本文介绍了如何在三个IEnumerables上使用Zip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
使用 Linq 从 3 个集合创建项目

我按如下所示对两个序列进行了压缩.

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});

当然,它没有用.有没有办法部署 Zip 并结合我的目标?还有其他使用这种方法的方法吗?我是否需要压缩两个序列,然后在处理过程中将它们与第三个序列解压缩?

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?

此时,我将为循环创建一个简单的 循环,并为请求的结构创建 yield return .我是不是该?我在.Net 4上.

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.

推荐答案

您可以对现有的 Zip 使用两次调用(虽然有点混乱,但是可以使用),或者您可以只需制作自己的 Zip (需要3个序列)即可.

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);
        }
    }
}

这篇关于如何在三个IEnumerables上使用Zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆