AsyncQueryable.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.Linq.Expressions;
  6. using System.Reflection;
  7. namespace System.Linq
  8. {
  9. /// <summary>
  10. /// Provides a set of extension methods for asynchronous enumerable sequences represented using expression trees.
  11. /// </summary>
  12. public static partial class AsyncQueryable
  13. {
  14. /// <summary>
  15. /// Converts the specified asynchronous enumerable sequence to an expression representation.
  16. /// </summary>
  17. /// <typeparam name="TElement">The type of the elements in the sequence.</typeparam>
  18. /// <param name="source">The asynchronous enumerable sequence to represent using an expression tree.</param>
  19. /// <returns>An asynchronous enumerable sequence using an expression tree to represent the specified asynchronous enumerable sequence.</returns>
  20. public static IAsyncQueryable<TElement> AsAsyncQueryable<TElement>(this IAsyncEnumerable<TElement> source)
  21. {
  22. if (source == null)
  23. {
  24. throw new ArgumentNullException(nameof(source));
  25. }
  26. if (source is IAsyncQueryable<TElement> queryable)
  27. {
  28. return queryable;
  29. }
  30. return new AsyncEnumerableQuery<TElement>(source);
  31. }
  32. #if HAS_VALUETUPLE
  33. private static MethodInfo s_Zip__TFirst_TSecond__2__0;
  34. private static MethodInfo Zip__TFirst_TSecond__2__0(Type TFirst, Type TSecond) =>
  35. (s_Zip__TFirst_TSecond__2__0 ??
  36. (s_Zip__TFirst_TSecond__2__0 = new Func<IAsyncQueryable<object>, IAsyncEnumerable<object>, IAsyncQueryable<ValueTuple<object, object>>>(Zip<object, object>).GetMethodInfo().GetGenericMethodDefinition())).MakeGenericMethod(TFirst, TSecond);
  37. public static IAsyncQueryable<(TFirst First, TSecond Second)> Zip<TFirst, TSecond>(this IAsyncQueryable<TFirst> first, IAsyncEnumerable<TSecond> second)
  38. {
  39. if (first == null)
  40. throw new ArgumentNullException(nameof(first));
  41. if (second == null)
  42. throw new ArgumentNullException(nameof(second));
  43. return first.Provider.CreateQuery<(TFirst, TSecond)>(Expression.Call(s_Zip__TFirst_TSecond__2__0(typeof(TFirst), typeof(TSecond)), first.Expression, GetSourceExpression(second)));
  44. }
  45. #endif
  46. private static Expression GetSourceExpression<TSource>(IAsyncEnumerable<TSource> source)
  47. {
  48. if (source is IAsyncQueryable<TSource> queryable)
  49. {
  50. return queryable.Expression;
  51. }
  52. return Expression.Constant(source, typeof(IAsyncEnumerable<TSource>));
  53. }
  54. }
  55. }