DefaultIfEmpty.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 CreateEnumerable(
  18. () =>
  19. {
  20. var done = false;
  21. var hasElements = false;
  22. var e = source.GetEnumerator();
  23. var current = default(TSource);
  24. var cts = new CancellationTokenDisposable();
  25. var d = Disposable.Create(cts, e);
  26. var f = default(Func<CancellationToken, Task<bool>>);
  27. f = async ct =>
  28. {
  29. if (done)
  30. return false;
  31. if (await e.MoveNext(ct)
  32. .ConfigureAwait(false))
  33. {
  34. hasElements = true;
  35. current = e.Current;
  36. return true;
  37. }
  38. done = true;
  39. if (!hasElements)
  40. {
  41. current = defaultValue;
  42. return true;
  43. }
  44. return false;
  45. };
  46. return CreateEnumerator(
  47. f,
  48. () => current,
  49. d.Dispose,
  50. e
  51. );
  52. });
  53. }
  54. public static IAsyncEnumerable<TSource> DefaultIfEmpty<TSource>(this IAsyncEnumerable<TSource> source)
  55. {
  56. if (source == null)
  57. throw new ArgumentNullException(nameof(source));
  58. return source.DefaultIfEmpty(default(TSource));
  59. }
  60. }
  61. }