Saadi
Saadi

Reputation: 2237

Enumerable.Zip alternative solution in Dot Net 3.0

I want to know that is there any alternative solution available in Dot Net 3.0 for Enumerable.Zip.

Here is the example that I want to implement:

I'm having two list of string.

var list1 = new string[] { "1", "2", "3" };
var list2 = new string[] { "a", "b", "c" };

I want to combine these lists, in such a way that it returns output like this:

{(1,a), (2,b), (3,c)}

I know, I can do this my using Zip in Dot Net >= 4.0. Using this way:

list1.Zip(list2, (x, y) => new Tuple<int, string>(x, y));

But, my problem is that I want to do the same in Dot Net 3.0. Is there any alternative method available in Dot Net <= 3.0 or I've to create custom method?

Upvotes: 1

Views: 665

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39956

As you know it is not available in .NET 3.5 and older version of it. However there is an implementation of it by Eric Lippert here https://blogs.msdn.microsoft.com/ericlippert/2009/05/07/zip-me-up/:

The code to do so is pretty trivial; if you happen to need this in C# 3.0, I’ve put the source code below.

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>
    (this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    if (first == null) throw new ArgumentNullException("first");
    if (second == null) throw new ArgumentNullException("second");
    if (resultSelector == null) throw new ArgumentNullException("resultSelector");
    return ZipIterator(first, second, resultSelector);
}

private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>
    (IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    using (IEnumerator<TFirst> e1 = first.GetEnumerator())
        using (IEnumerator<TSecond> e2 = second.GetEnumerator())
            while (e1.MoveNext() && e2.MoveNext())
                yield return resultSelector(e1.Current, e2.Current);
} 

Upvotes: 2

Related Questions