Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve ambiguous ZIP call between Enumerable and MoreLINQ?

I've ran into problem with extension method resolution. LINQ and MoreLINQ contain zip method, it was present in .NET since 4.0 version and was always in MoreLINQ library. But you can't use one of the implementation with nice-old extension method syntax. So this code won't compile

using MoreLinq;
using System.Linq;


var students = new [] { "Mark", "Bob", "David" };
var colors = new [] { "Pink", "Red", "Blue" };

students.Zip(colors, (s, c) => s + c );

Error:

The call is ambiguous between the following methods or properties: 
'MoreLinq.MoreEnumerable.Zip<string,string,string>
(System.Collections.Generic.IEnumerable<string>, 
System.Collections.Generic.IEnumerable<string>, System.Func<string,string,string>)' and 
'System.Linq.Enumerable.Zip<string,string,string>
(System.Collections.Generic.IEnumerable<string>, 
System.Collections.Generic.IEnumerable<string>, System.Func<string,string,string>)'

I've found good resolution for Concat method on string for MoreLINQ made by Jon Skeet at this post, but I'm not aware of good resolution for zip method.

NOTE: You can always use static method call syntax and it all works fine with

MoreEnumerable.Zip(students, colors, (s, c) => s + c )

but misses the point of extension syntax sugar a little bit. If you have lots of data transformation with LINQ and MoreLINQ calls - you don't want to use static method call in the middle.

Are there any better ways to resolve this ambiguity?

like image 269
Ilya Ivanov Avatar asked Jan 18 '13 10:01

Ilya Ivanov


2 Answers

A way to make it compile would be:

var students = new[] { "Mark", "Bob", "David", "test" }.AsQueryable();
var colors = new[] { "Pink", "Red", "Blue" };

students
    .Zip(colors, (s, c) => s + c)
    .Dump();

The students object has to be converted to an IQueryable object.

like image 75
Alex Filipovici Avatar answered Sep 23 '22 01:09

Alex Filipovici


You can create a wrapper class with the same method, but diffrent name. It's a bit dirty, but if you really like to have extension syntax, that is the only way.

public static class MoreLinqWrapper
{
    public static IEnumerable<TResult> MlZip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
    {
        return MoreLinq.Zip(first, second, resultSelector);
    }
}
like image 35
Vladimir Perevalov Avatar answered Sep 22 '22 01:09

Vladimir Perevalov