.net6 & MoreLinq : Call is ambiguous between System.Linq.Enumerable.DistinctBy and MoreLinq.MoreEnumerable.DistinctBy

Recently I upgraded one of my projects to use .NET 6. Earlier I was using MoreLinq library to use DistinctBy() to apply it on the specific property.

Now as I upgraded TargetFramework to .NET 6, this change come up with inbuilt support to DistinctBy().

Now the compiler is confused about which DistinctBy() needs to select, I can't rely on System.Linq, because the removal of using MoreLinq will cause multiple other errors.

I know if we face ambiguity between the same methods then we can use using alias, but I am not sure how to use using alias for Linq extension methods.

Here is the error:

enter image description here

I am able to replicate the same issue in the below fiddle

Try online


Solution 1:

To avoid conflicts when using MoreLinq, while still using them as extension methods, you can import the MoreLinq methods that you need like this:

using static MoreLinq.Extensions.LagExtension;
using static MoreLinq.Extensions.LeadExtension;

So in your case you could just delete MoreLinq from your usings and then import any MoreLinq extension methods that you need in the file individually as shown above.

You can read about it on the MoreLinq Github page

Solution 2:

You can't alias an extension method, but you can call the extension like a normal method, using the full namespace. After all, extension methods are really just syntactic sugar. For example (using the same data you provided in your fiddle):

var inputs =  new []
{
    new {Name = "Bruce wayne", State = "New York"},
    new {Name = "Rajnikant", State = "Tamil Nadu"},
    new {Name = "Robert Downey jr", State = "Pennsylvania"},
    new {Name = "Dwane Johnson", State = "Pennsylvania"},
    new {Name = "Hritik", State = "Maharashtra"}
};
    
var net6DistinctBy = System.Linq.Enumerable.DistinctBy(inputs, x => x.State);
var moreLinqDistinctBy = MoreLinq.MoreEnumerable.DistinctBy(inputs, x => x.State);