Concat.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerableEx
  10. {
  11. public static IAsyncEnumerable<TSource> Concat<TSource>(this IAsyncEnumerable<IAsyncEnumerable<TSource>> sources)
  12. {
  13. if (sources == null)
  14. throw Error.ArgumentNull(nameof(sources));
  15. return AsyncEnumerable.Create(Core);
  16. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  17. {
  18. await foreach (var source in sources.WithCancellation(cancellationToken).ConfigureAwait(false))
  19. {
  20. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  21. {
  22. yield return item;
  23. }
  24. }
  25. }
  26. }
  27. public static IAsyncEnumerable<TSource> Concat<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  28. {
  29. if (sources == null)
  30. throw Error.ArgumentNull(nameof(sources));
  31. return AsyncEnumerable.Create(Core);
  32. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  33. {
  34. foreach (var source in sources)
  35. {
  36. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  37. {
  38. yield return item;
  39. }
  40. }
  41. }
  42. }
  43. public static IAsyncEnumerable<TSource> Concat<TSource>(params IAsyncEnumerable<TSource>[] sources)
  44. {
  45. if (sources == null)
  46. throw Error.ArgumentNull(nameof(sources));
  47. return AsyncEnumerable.Create(Core);
  48. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  49. {
  50. foreach (var source in sources)
  51. {
  52. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  53. {
  54. yield return item;
  55. }
  56. }
  57. }
  58. }
  59. }
  60. }