You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同时使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:05:18