How to use zip for three IEnumerables

Possible duplicate:
Create items from 3 collections using Linq

I performed a zippage of two sequences as follows.

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

Now I realized that I will use three sequences, not two. So I tried redesigning the code like this:

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

Of course, this did not work. Is there a way to deploy Zip to include what I'm aiming for? Is there any other way to use this? Should I fasten two of the sequences and then fasten them by third unpacking in the process?

At this point, I'm going to create a simple for -loop and yield return requested structure. Do I need to? I'm on .Net 4.

+6
source share
1 answer

You can use two calls to an existing Zip (that would be a little messy, but it worked), or you could just create your own Zip that accepts 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); } } } 
+10
source

Source: https://habr.com/ru/post/926514/


All Articles