Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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);
    }
}

Update your morelinq, and from now

  • Use Zip for .NET 4.0 Zip
  • Use ZipShortest for MoreLinq Zip

Problem is fixed in 88c573f7

Unfortunately, the static method call syntax is the only way here.

I ran into this the other day and I simply called the MoreLinq method directly.

MoreLinq.MoreEnumerable.Zip(students, colors, (s, c) => s + c);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top