DefaultIfEmpty.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<TSource> DefaultIfEmpty<TSource>(this IAsyncEnumerable<TSource> source, TSource defaultValue)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. return Create(() =>
  18. {
  19. var done = false;
  20. var hasElements = false;
  21. var e = source.GetEnumerator();
  22. var current = default(TSource);
  23. var cts = new CancellationTokenDisposable();
  24. var d = Disposable.Create(cts, e);
  25. var f = default(Func<CancellationToken, Task<bool>>);
  26. f = async ct =>
  27. {
  28. if (done)
  29. return false;
  30. if (await e.MoveNext(ct)
  31. .ConfigureAwait(false))
  32. {
  33. hasElements = true;
  34. current = e.Current;
  35. return true;
  36. }
  37. done = true;
  38. if (!hasElements)
  39. {
  40. current = defaultValue;
  41. return true;
  42. }
  43. return false;
  44. };
  45. return Create(
  46. f,
  47. () => current,
  48. d.Dispose,
  49. e
  50. );
  51. });
  52. }
  53. public static IAsyncEnumerable<TSource> DefaultIfEmpty<TSource>(this IAsyncEnumerable<TSource> source)
  54. {
  55. if (source == null)
  56. throw new ArgumentNullException(nameof(source));
  57. return source.DefaultIfEmpty(default(TSource));
  58. }
  59. }
  60. }