質問するログイン新規登録

回答編集履歴

1

Maxima

2025/07/23 06:21

投稿

TN8001
TN8001

スコア10166

answer CHANGED
@@ -38,4 +38,28 @@
38
38
  public override int Compare(FileInfo? x, FileInfo? y)
39
39
  => Comparer<long?>.Default.Compare(x?.Length, y?.Length);
40
40
  }
41
- ```
41
+ ```
42
+
43
+ ---
44
+
45
+ 最大値の要素が複数あった場合、`MaxBy`は要素ひとつしか返しません。
46
+ すべて列挙したいなら`MaxBy`は使えません。
47
+
48
+ 一度`Max`を求めて`Where`するとか、`GroupBy`して`MaxBy`するとかひと工夫必要です。
49
+ 面倒だったら[MoreLINQ](https://www.nuget.org/packages/morelinq/)の[Maxima](https://morelinq.github.io/4.4/ref/api/html/Overload_MoreLinq_MoreEnumerable_Maxima.htm)を使うのも手です。
50
+
51
+ ```cs
52
+ using static MoreLinq.Extensions.MaximaExtension;
53
+
54
+ int[] array = [-5, 3, -1, 5];
55
+ Console.WriteLine(array.MaxBy(Math.Abs)); // -5
56
+
57
+ var absMax = array.Max(Math.Abs);
58
+ Console.WriteLine(string.Join(", ", array.Where(x => Math.Abs(x) == absMax))); // -5, 5
59
+ Console.WriteLine(string.Join(", ", array.GroupBy(Math.Abs).MaxBy(g => g.Key)!)); // -5, 5
60
+ Console.WriteLine(string.Join(", ", array.Maxima(Math.Abs))); // -5, 5
61
+ ```
62
+
63
+ [LINQ で最小値・最大値を柔軟に求める](https://zenn.dev/zuishin/articles/2018_03_22_95e171eccc128bdd6429)
64
+ [c# - Linq MaxBy with all elements? - Stack Overflow](https://stackoverflow.com/questions/69863141)
65
+ [c# - MaxBy() is there a way to get multiple max values? - Stack Overflow](https://stackoverflow.com/questions/74508206)