Enumerable.MaxBy 方法

定义

重载

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根据指定的键选择器函数返回泛型序列中的最大值。

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

根据指定的键选择器函数和键比较器返回泛型序列中的最大值。

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

Source:
Max.cs
Source:
Max.cs
Source:
Max.cs

根据指定的键选择器函数返回泛型序列中的最大值。

C#
public static TSource? MaxBy<TSource,TKey> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TKey> keySelector);

类型参数

TSource

source的元素的类型。

TKey

要比较元素依据的键的类型。

参数

source
IEnumerable<TSource>

要确定最大值的值序列。

keySelector
Func<TSource,TKey>

用于提取每个元素的键的函数。

返回

TSource

序列中具有最大键的值。

例外

source null

source 中提取的键不实现 IComparableIComparable<T> 接口。

TSource 是基元类型,源序列为空。

注解

如果源序列为空,则根据源类型,两个可能的结果是可能的。 如果 TSource 为可以为 null 的类型,此方法将返回 null。 如果 TSource 是不可为 null 的结构,例如基元类型,则会引发 InvalidOperationException

如果源序列仅包含 null的值,此方法将返回 null

适用于

.NET 9 和其他版本
产品 版本
.NET 6, 7, 8, 9

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

Source:
Max.cs
Source:
Max.cs
Source:
Max.cs

根据指定的键选择器函数和键比较器返回泛型序列中的最大值。

C#
public static TSource? MaxBy<TSource,TKey> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TKey> keySelector, System.Collections.Generic.IComparer<TKey>? comparer);

类型参数

TSource

source的元素的类型。

TKey

要比较元素依据的键的类型。

参数

source
IEnumerable<TSource>

要确定最大值的值序列。

keySelector
Func<TSource,TKey>

用于提取每个元素的键的函数。

comparer
IComparer<TKey>

要比较键的 IComparer<T>

返回

TSource

序列中具有最大键的值。

例外

source null

source 中提取的键不实现 IComparableIComparable<T> 接口。

TSource 是基元类型,源序列为空。

注解

如果源序列为空,则根据源类型,两个可能的结果是可能的。 如果 TSource 为可以为 null 的类型,此方法将返回 null。 如果 TSource 是不可为 null 的结构,例如基元类型,则会引发 InvalidOperationException

如果源序列仅包含 null的值,此方法将返回 null

适用于

.NET 9 和其他版本
产品 版本
.NET 6, 7, 8, 9