1
0

Create.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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;
  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. throw new ArgumentNullException(nameof(getEnumerator));
  20. return new AnonymousEnumerable<TResult>(getEnumerator);
  21. }
  22. /// <summary>
  23. /// Creates an enumerable sequence based on an asynchronous method that provides a yielder.
  24. /// </summary>
  25. /// <typeparam name="T">Result sequence element type.</typeparam>
  26. /// <param name="create">
  27. /// Delegate implementing an asynchronous method that can use the specified yielder to yield return
  28. /// values.
  29. /// </param>
  30. /// <returns>Sequence that will use the asynchronous method to obtain its elements.</returns>
  31. public static IEnumerable<T> Create<T>(Action<IYielder<T>> create)
  32. {
  33. if (create == null)
  34. throw new ArgumentNullException(nameof(create));
  35. foreach (var x in new Yielder<T>(create))
  36. {
  37. yield return x;
  38. }
  39. }
  40. private sealed class AnonymousEnumerable<TResult>(Func<IEnumerator<TResult>> getEnumerator) : IEnumerable<TResult>
  41. {
  42. public IEnumerator<TResult> GetEnumerator() => getEnumerator();
  43. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  44. }
  45. }
  46. }