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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With