Cast.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  14. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.cast?view=net-9.0-pp
  15. /// <summary>
  16. /// Converts the elements of an async-enumerable sequence to the specified type.
  17. /// </summary>
  18. /// <typeparam name="TResult">The type to convert the elements in the source sequence to.</typeparam>
  19. /// <param name="source">The async-enumerable sequence that contains the elements to be converted.</param>
  20. /// <returns>An async-enumerable sequence that contains each element of the source sequence converted to the specified type.</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  22. public static IAsyncEnumerable<TResult> Cast<TResult>(this IAsyncEnumerable<object> source)
  23. {
  24. if (source == null)
  25. throw Error.ArgumentNull(nameof(source));
  26. if (source is IAsyncEnumerable<TResult> typedSource)
  27. {
  28. return typedSource;
  29. }
  30. return Core(source);
  31. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<object> source, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  32. {
  33. await foreach (var obj in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  34. {
  35. yield return (TResult)obj;
  36. }
  37. }
  38. }
  39. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  40. }
  41. }