DefaultIfEmpty.cs 6.2 KB

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