Distinct.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  12. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.distinct?view=net-9.0-pp
  13. // These two overloads are covered by a single method in System.Linq.AsyncEnumerable. Its only method
  14. // takes a comparer, but specifies a default value of null.
  15. /// <summary>
  16. /// Returns an async-enumerable sequence that contains only distinct elements.
  17. /// </summary>
  18. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  19. /// <param name="source">An async-enumerable sequence to retain distinct elements for.</param>
  20. /// <returns>An async-enumerable sequence only containing the distinct elements from the source sequence.</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  22. /// <remarks>Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.</remarks>
  23. public static IAsyncEnumerable<TSource> Distinct<TSource>(this IAsyncEnumerable<TSource> source) => Distinct(source, comparer: null);
  24. /// <summary>
  25. /// Returns an async-enumerable sequence that contains only distinct elements according to the comparer.
  26. /// </summary>
  27. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  28. /// <param name="source">An async-enumerable sequence to retain distinct elements for.</param>
  29. /// <param name="comparer">Equality comparer for source elements.</param>
  30. /// <returns>An async-enumerable sequence only containing the distinct elements from the source sequence.</returns>
  31. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="comparer"/> is null.</exception>
  32. /// <remarks>Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.</remarks>
  33. public static IAsyncEnumerable<TSource> Distinct<TSource>(this IAsyncEnumerable<TSource> source, IEqualityComparer<TSource>? comparer)
  34. {
  35. if (source == null)
  36. throw Error.ArgumentNull(nameof(source));
  37. return new DistinctAsyncIterator<TSource>(source, comparer);
  38. }
  39. private sealed class DistinctAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  40. {
  41. private readonly IEqualityComparer<TSource>? _comparer;
  42. private readonly IAsyncEnumerable<TSource> _source;
  43. private IAsyncEnumerator<TSource>? _enumerator;
  44. private Set<TSource>? _set;
  45. public DistinctAsyncIterator(IAsyncEnumerable<TSource> source, IEqualityComparer<TSource>? comparer)
  46. {
  47. _source = source;
  48. _comparer = comparer;
  49. }
  50. public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  51. {
  52. var s = await FillSetAsync(cancellationToken).ConfigureAwait(false);
  53. return s.ToArray();
  54. }
  55. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  56. {
  57. var s = await FillSetAsync(cancellationToken).ConfigureAwait(false);
  58. return s.ToList();
  59. }
  60. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  61. {
  62. if (onlyIfCheap)
  63. {
  64. return new ValueTask<int>(-1);
  65. }
  66. return Core();
  67. async ValueTask<int> Core()
  68. {
  69. var s = await FillSetAsync(cancellationToken).ConfigureAwait(false);
  70. return s.Count;
  71. }
  72. }
  73. public override AsyncIteratorBase<TSource> Clone()
  74. {
  75. return new DistinctAsyncIterator<TSource>(_source, _comparer);
  76. }
  77. public override async ValueTask DisposeAsync()
  78. {
  79. if (_enumerator != null)
  80. {
  81. await _enumerator.DisposeAsync().ConfigureAwait(false);
  82. _enumerator = null;
  83. _set = null;
  84. }
  85. await base.DisposeAsync().ConfigureAwait(false);
  86. }
  87. protected override async ValueTask<bool> MoveNextCore()
  88. {
  89. switch (_state)
  90. {
  91. case AsyncIteratorState.Allocated:
  92. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  93. if (!await _enumerator.MoveNextAsync().ConfigureAwait(false))
  94. {
  95. await DisposeAsync().ConfigureAwait(false);
  96. return false;
  97. }
  98. var element = _enumerator.Current;
  99. _set = new Set<TSource>(_comparer);
  100. _set.Add(element);
  101. _current = element;
  102. _state = AsyncIteratorState.Iterating;
  103. return true;
  104. case AsyncIteratorState.Iterating:
  105. while (await _enumerator!.MoveNextAsync().ConfigureAwait(false))
  106. {
  107. element = _enumerator.Current;
  108. if (_set!.Add(element))
  109. {
  110. _current = element;
  111. return true;
  112. }
  113. }
  114. break;
  115. }
  116. await DisposeAsync().ConfigureAwait(false);
  117. return false;
  118. }
  119. private Task<Set<TSource>> FillSetAsync(CancellationToken cancellationToken)
  120. {
  121. return AsyncEnumerableHelpers.ToSet(_source, _comparer, cancellationToken);
  122. }
  123. }
  124. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  125. }
  126. }