Create.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class EnumerableEx
  12. {
  13. /// <summary>
  14. /// Creates an enumerable sequence based on an enumerator factory function.
  15. /// </summary>
  16. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  17. /// <param name="getEnumerator">Enumerator factory function.</param>
  18. /// <returns>Sequence that will invoke the enumerator factory upon a call to GetEnumerator.</returns>
  19. public static IEnumerable<TResult> Create<TResult>(Func<IEnumerator<TResult>> getEnumerator)
  20. {
  21. if (getEnumerator == null)
  22. throw new ArgumentNullException(nameof(getEnumerator));
  23. return new AnonymousEnumerable<TResult>(getEnumerator);
  24. }
  25. /// <summary>
  26. /// Creates an enumerable sequence based on an asynchronous method that provides a yielder.
  27. /// </summary>
  28. /// <typeparam name="T">Result sequence element type.</typeparam>
  29. /// <param name="create">
  30. /// Delegate implementing an asynchronous method that can use the specified yielder to yield return
  31. /// values.
  32. /// </param>
  33. /// <returns>Sequence that will use the asynchronous method to obtain its elements.</returns>
  34. public static IEnumerable<T> Create<T>(Action<IYielder<T>> create)
  35. {
  36. if (create == null)
  37. throw new ArgumentNullException(nameof(create));
  38. foreach (var x in new Yielder<T>(create))
  39. yield return x;
  40. }
  41. private class AnonymousEnumerable<TResult> : IEnumerable<TResult>
  42. {
  43. private readonly Func<IEnumerator<TResult>> _getEnumerator;
  44. public AnonymousEnumerable(Func<IEnumerator<TResult>> getEnumerator)
  45. {
  46. _getEnumerator = getEnumerator;
  47. }
  48. public IEnumerator<TResult> GetEnumerator()
  49. {
  50. return _getEnumerator();
  51. }
  52. IEnumerator IEnumerable.GetEnumerator()
  53. {
  54. return GetEnumerator();
  55. }
  56. }
  57. }
  58. }