如何解决Enumerable和MoreLINQ之间模棱两可的ZIP调用

本文关键字:之间 MoreLINQ 模棱两可 调用 ZIP Enumerable 何解决 解决 | 更新日期: 2023-09-27 17:54:03

我遇到了扩展方法解析的问题。LINQ和MoreLINQ包含zip方法,它从。net 4.0版本开始就存在,并且一直存在于MoreLINQ库中。但是,您不能使用具有旧的扩展方法语法的实现。所以这段代码不能编译

using MoreLinq;
using System.Linq;

var students = new [] { "Mark", "Bob", "David" };
var colors = new [] { "Pink", "Red", "Blue" };
students.Zip(colors, (s, c) => s + c );
错误:

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>)'

我在Jon Skeet的这篇文章中找到了Concat方法对MoreLINQ的string的良好分辨率,但我不知道zip方法的良好分辨率。

注意:你总是可以使用静态方法调用语法,它在

中工作得很好
MoreEnumerable.Zip(students, colors, (s, c) => s + c )

但是忽略了扩展语法糖的一点。如果你需要使用LINQ和MoreLINQ调用进行大量的数据转换,你不会希望在中间使用静态方法调用。

是否有更好的方法来解决这种歧义?

如何解决Enumerable和MoreLINQ之间模棱两可的ZIP调用

您可以使用相同的方法创建一个包装器类,但名称不同。这有点脏,但如果您真的想要扩展语法,这是唯一的方法。

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

让它编译的方法是:

var students = new[] { "Mark", "Bob", "David", "test" }.AsQueryable();
var colors = new[] { "Pink", "Red", "Blue" };
students
    .Zip(colors, (s, c) => s + c)
    .Dump();

students对象必须转换为IQueryable对象

更新你的morelinq,从现在开始

  • 使用Zip为。net 4.0 Zip
  • 使用ZipShortest for MoreLinq Zip

修复88c573f7

的问题

前几天我遇到了这个问题,我直接调用了MoreLinq方法。

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

不幸的是,静态方法调用语法是这里唯一的方法。