同时使用Linq与MoreLinq引发方法歧义及FirstOrDefault报错的解决方案咨询
我有一段用MoreLinq编写的C#代码:
var maxPage = _pageState?.Value?.Pages?.MaxBy(p => p.Type.Grids["desktop"].ColCount)?.FirstOrDefault();
由于解决方案同时引用了Linq和MoreLinq,出现了以下歧义错误:
The call is ambiguous between the following methods or properties: 'MoreLinq.MoreEnumerable.DistinctBy<TSource, TKey>(System.Collections.Generic.IEnumerable, System.Func<TSource, TKey>)' and 'System.Linq.Enumerable.DistinctBy<TSource, TKey>(System.Collections.Generic.IEnumerable, System.Func<TSource, TKey>)
我尝试在代码中添加静态扩展MoreLinq.Extensions.AppendExtension,但代码末尾的FirstOrDefault()又报了新错误:
'MyClass' does not contain a definition for 'FirstOrDefault' and no accessible extension method 'FirstOrDefault' accepting a first argument of type 'MyClass' could be found (are you missing a using directive or an assembly reference?)
移除MoreLinq后,FirstOrDefault的缺失错误依然存在,请问最佳解决方式是什么?
1. 消除Linq与MoreLinq的方法歧义
Linq和MoreLinq存在DistinctBy这类同名扩展方法,导致编译器无法判断调用目标。可以通过直接调用静态类方法而非扩展方法语法来明确指定:
// 明确使用MoreLinq的DistinctBy实现 MoreLinq.MoreEnumerable.DistinctBy(yourCollection, item => item.Key); // 或者明确使用System.Linq的DistinctBy实现 System.Linq.Enumerable.DistinctBy(yourCollection, item => item.Key);
2. 修复FirstOrDefault()报错
报错核心是MaxBy的返回值类型差异:
- MoreLinq的
MaxBy返回包含所有最大值元素的序列(IEnumerable<MyClass>),因此可以链式调用FirstOrDefault(); - .NET 6+原生Linq的
MaxBy直接返回单个元素(MyClass),不是序列,自然没有FirstOrDefault()方法。
针对你的代码,分两种场景修正:
场景A:继续使用MoreLinq的MaxBy
明确指定调用MoreLinq的静态方法,保留FirstOrDefault():
var maxPage = _pageState?.Value?.Pages != null ? MoreLinq.MoreEnumerable.MaxBy(_pageState.Value.Pages, p => p.Type.Grids["desktop"].ColCount).FirstOrDefault() : null;
场景B:改用原生Linq的MaxBy(.NET 6+支持)
原生方法直接返回单个元素,无需FirstOrDefault(),简化代码:
var maxPage = _pageState?.Value?.Pages?.MaxBy(p => p.Type.Grids["desktop"].ColCount);
3. 长期避免冲突的方案
- 仅在需要使用MoreLinq独有方法的文件中添加
using MoreLinq;,全局移除不必要的引用; - 给MoreLinq添加别名,在文件顶部声明:
using ML = MoreLinq.MoreEnumerable;
之后调用时用别名明确指定:
ML.MaxBy(collection, selector);
内容的提问来源于stack exchange,提问作者Adil15

