开发者

Combine 3 sequences

I have three s开发者_开发百科tring arrays. I want to combine them using zip in linq. How to do?

arr1.Zip(arr2, (a1, a2) => a1 + a2);

How to add arr3?


You can use Zip again:

arr1.Zip(arr2, (a1, a2) => new { a1, a2 })
    .Zip(arr3, (a12, a3) => a12.a1 + a12.a2 + a3)

or

arr1.Zip(arr2, (a1, a2) => a1 + a2)
    .Zip(arr3, (a12, a3) => a12 + a3)

The former version avoids one extra string concatenation.


I prefer using a custom Zip which takes as many sequences as you need.

public static IEnumerable Zip(
    this IEnumerable first,
    IEnumerable second,
    IEnumerable third,
    Func resultSelector )
{
    Contract.Requires(
        first != null && second != null && third != null && resultSelector != null );

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

This is basically Jon Skeet's implementation with one extra parameter, so all credit goes to him. ;p I believe this has some advantages in some scenarios, where you would otherwise need intermediate objects. I definitely find it clearer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜