Cast.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 AsyncEnumerable
  10. {
  11. // NB: This is a non-standard LINQ operator, because we don't have a non-generic IAsyncEnumerable.
  12. // We're keeping it to enable `from T x in xs` binding in C#.
  13. /// <summary>
  14. /// Converts the elements of an async-enumerable sequence to the specified type.
  15. /// </summary>
  16. /// <typeparam name="TResult">The type to convert the elements in the source sequence to.</typeparam>
  17. /// <param name="source">The async-enumerable sequence that contains the elements to be converted.</param>
  18. /// <returns>An async-enumerable sequence that contains each element of the source sequence converted to the specified type.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  20. public static IAsyncEnumerable<TResult> Cast<TResult>(this IAsyncEnumerable<object> source)
  21. {
  22. if (source == null)
  23. throw Error.ArgumentNull(nameof(source));
  24. if (source is IAsyncEnumerable<TResult> typedSource)
  25. {
  26. return typedSource;
  27. }
  28. return Create(Core);
  29. async IAsyncEnumerator<TResult> Core(CancellationToken cancellationToken)
  30. {
  31. await foreach (var obj in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  32. {
  33. yield return (TResult)obj;
  34. }
  35. }
  36. }
  37. }
  38. }