Create.cs 2.5 KB

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