ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Zip

Merges three sequences by using the specified predicate function.

Source

public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(
	this IEnumerable<TFirst> first,
	IEnumerable<TSecond> second,
	IEnumerable<TThird> third,
	Func<TFirst, TSecond, TThird, TResult> resultSelector )
{
	Contract.Requires( first != null && second != null && third != null && resultSelector != null );

	using ( IEnumerator<TFirst> iterator1 = first.GetEnumerator() )
	using ( IEnumerator<TSecond> iterator2 = second.GetEnumerator() )
	using ( IEnumerator<TThird> iterator3 = third.GetEnumerator() )
	{
		while ( iterator1.MoveNext() && iterator2.MoveNext() && iterator3.MoveNext() )
		{
			yield return resultSelector( iterator1.Current, iterator2.Current, iterator3.Current );
		}
	}
}

Example

byte[] reds = new { 0, 1, 2 };
byte[] greens = new { 3, 4, 5 };
byte[] blues = new { 6, 7, 8 };
var mergedColors = reds.Zip( greens, blues, Color.FromRgb );

Author: Steven Jeuris

Submitted on: 15 nov. 2011

Language: C#

Type: System.IEnumerable<T>

Views: 6257