Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Zip on three IEnumerables [duplicate]

Tags:

c#

linq

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.

like image 544
Konrad Viltersten Avatar asked Sep 28 '12 13:09

Konrad Viltersten


1 Answers

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);
        }
    }
}
like image 90
Servy Avatar answered Oct 07 '22 17:10

Servy