Cast.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. #if REFERENCE_ASSEMBLY
  10. public static partial class AsyncEnumerableDeprecated
  11. #else
  12. public static partial class AsyncEnumerable
  13. #endif
  14. {
  15. // NB: This is a non-standard LINQ operator, because we don't have a non-generic IAsyncEnumerable.
  16. // We're keeping it to enable `from T x in xs` binding in C#.
  17. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  18. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.cast?view=net-9.0-pp
  19. /// <summary>
  20. /// Converts the elements of an async-enumerable sequence to the specified type.
  21. /// </summary>
  22. /// <typeparam name="TResult">The type to convert the elements in the source sequence to.</typeparam>
  23. /// <param name="source">The async-enumerable sequence that contains the elements to be converted.</param>
  24. /// <returns>An async-enumerable sequence that contains each element of the source sequence converted to the specified type.</returns>
  25. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  26. public static IAsyncEnumerable<TResult> Cast<TResult>(this IAsyncEnumerable<object> source)
  27. {
  28. if (source == null)
  29. throw Error.ArgumentNull(nameof(source));
  30. if (source is IAsyncEnumerable<TResult> typedSource)
  31. {
  32. return typedSource;
  33. }
  34. return Core(source);
  35. static async IAsyncEnumerable<TResult> Core(IAsyncEnumerable<object> source, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  36. {
  37. await foreach (var obj in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  38. {
  39. yield return (TResult)obj;
  40. }
  41. }
  42. }
  43. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  44. }
  45. }