MaxBy.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. #if !(REFERENCE_ASSEMBLY && NET6_0_OR_GREATER)
  10. /// <summary>
  11. /// Returns the elements with the maximum key value by using the default comparer to compare key values.
  12. /// </summary>
  13. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  14. /// <typeparam name="TKey">Key type.</typeparam>
  15. /// <param name="source">Source sequence.</param>
  16. /// <param name="keySelector">Key selector used to extract the key for each element in the sequence.</param>
  17. /// <returns>List with the elements that share the same maximum key value.</returns>
  18. [Obsolete("Use MaxByWithTies to maintain same behavior with .NET 6 and later", false)]
  19. public static IList<TSource> MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  20. {
  21. if (source == null)
  22. throw new ArgumentNullException(nameof(source));
  23. if (keySelector == null)
  24. throw new ArgumentNullException(nameof(keySelector));
  25. return MaxBy(source, keySelector, Comparer<TKey>.Default);
  26. }
  27. /// <summary>
  28. /// Returns the elements with the minimum key value by using the specified comparer to compare key values.
  29. /// </summary>
  30. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  31. /// <typeparam name="TKey">Key type.</typeparam>
  32. /// <param name="source">Source sequence.</param>
  33. /// <param name="keySelector">Key selector used to extract the key for each element in the sequence.</param>
  34. /// <param name="comparer">Comparer used to determine the maximum key value.</param>
  35. /// <returns>List with the elements that share the same maximum key value.</returns>
  36. [Obsolete("Use MaxByWithTies to maintain same behavior with .NET 6 and later", false)]
  37. public static IList<TSource> MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
  38. {
  39. if (source == null)
  40. throw new ArgumentNullException(nameof(source));
  41. if (keySelector == null)
  42. throw new ArgumentNullException(nameof(keySelector));
  43. if (comparer == null)
  44. throw new ArgumentNullException(nameof(comparer));
  45. return ExtremaBy(source, keySelector, (key, minValue) => comparer.Compare(key, minValue));
  46. }
  47. #endif
  48. }
  49. }