DefaultIfEmpty.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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;
  5. using System.Collections.Generic;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  13. /// <summary>
  14. /// Returns the elements of the specified sequence or the type parameter's default value in a singleton sequence if the sequence is empty.
  15. /// </summary>
  16. /// <typeparam name="TSource">The type of the elements in the source sequence (if any), whose default value will be taken if the sequence is empty.</typeparam>
  17. /// <param name="source">The sequence to return a default value for if it is empty.</param>
  18. /// <returns>An async-enumerable sequence that contains the default value for the TSource type if the source is empty; otherwise, the elements of the source itself.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  20. public static IAsyncEnumerable<TSource> DefaultIfEmpty<TSource>(this IAsyncEnumerable<TSource> source) =>
  21. DefaultIfEmpty(source, default!);
  22. /// <summary>
  23. /// Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
  24. /// </summary>
  25. /// <typeparam name="TSource">The type of the elements in the source sequence (if any), and the specified default value which will be taken if the sequence is empty.</typeparam>
  26. /// <param name="source">The sequence to return the specified value for if it is empty.</param>
  27. /// <param name="defaultValue">The value to return if the sequence is empty.</param>
  28. /// <returns>An async-enumerable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.</returns>
  29. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  30. public static IAsyncEnumerable<TSource> DefaultIfEmpty<TSource>(this IAsyncEnumerable<TSource> source, TSource defaultValue)
  31. {
  32. if (source == null)
  33. throw Error.ArgumentNull(nameof(source));
  34. return new DefaultIfEmptyAsyncIterator<TSource>(source, defaultValue);
  35. }
  36. private sealed class DefaultIfEmptyAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>
  37. {
  38. private readonly IAsyncEnumerable<TSource> _source;
  39. private readonly TSource _defaultValue;
  40. private IAsyncEnumerator<TSource>? _enumerator;
  41. public DefaultIfEmptyAsyncIterator(IAsyncEnumerable<TSource> source, TSource defaultValue)
  42. {
  43. _source = source;
  44. _defaultValue = defaultValue;
  45. }
  46. public override AsyncIteratorBase<TSource> Clone()
  47. {
  48. return new DefaultIfEmptyAsyncIterator<TSource>(_source, _defaultValue);
  49. }
  50. public override async ValueTask DisposeAsync()
  51. {
  52. if (_enumerator != null)
  53. {
  54. await _enumerator.DisposeAsync().ConfigureAwait(false);
  55. _enumerator = null;
  56. }
  57. await base.DisposeAsync().ConfigureAwait(false);
  58. }
  59. protected override async ValueTask<bool> MoveNextCore()
  60. {
  61. switch (_state)
  62. {
  63. case AsyncIteratorState.Allocated:
  64. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  65. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  66. {
  67. _current = _enumerator.Current;
  68. _state = AsyncIteratorState.Iterating;
  69. }
  70. else
  71. {
  72. _current = _defaultValue;
  73. await _enumerator.DisposeAsync().ConfigureAwait(false);
  74. _enumerator = null;
  75. _state = AsyncIteratorState.Disposed;
  76. }
  77. return true;
  78. case AsyncIteratorState.Iterating:
  79. if (await _enumerator!.MoveNextAsync().ConfigureAwait(false))
  80. {
  81. _current = _enumerator.Current;
  82. return true;
  83. }
  84. break;
  85. }
  86. await DisposeAsync().ConfigureAwait(false);
  87. return false;
  88. }
  89. public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
  90. {
  91. var array = await _source.ToArrayAsync(cancellationToken).ConfigureAwait(false);
  92. return array.Length == 0 ? [_defaultValue] : array;
  93. }
  94. public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
  95. {
  96. var list = await _source.ToListAsync(cancellationToken).ConfigureAwait(false);
  97. if (list.Count == 0)
  98. {
  99. list.Add(_defaultValue);
  100. }
  101. return list;
  102. }
  103. public async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  104. {
  105. int count;
  106. if (!onlyIfCheap || _source is ICollection<TSource> || _source is ICollection)
  107. {
  108. count = await _source.CountAsync(cancellationToken).ConfigureAwait(false);
  109. }
  110. else if (_source is IAsyncIListProvider<TSource> listProv)
  111. {
  112. count = await listProv.GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  113. }
  114. else
  115. {
  116. count = -1;
  117. }
  118. return count == 0 ? 1 : count;
  119. }
  120. }
  121. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  122. }
  123. }