Distinct.cs 6.5 KB

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