Defer.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 enumerable factory function.
  12. /// </summary>
  13. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  14. /// <param name="enumerableFactory">Enumerable factory function.</param>
  15. /// <returns>Sequence that will invoke the enumerable factory upon a call to GetEnumerator.</returns>
  16. public static IEnumerable<TResult> Defer<TResult>(Func<IEnumerable<TResult>> enumerableFactory)
  17. {
  18. if (enumerableFactory == null)
  19. {
  20. throw new ArgumentNullException(nameof(enumerableFactory));
  21. }
  22. return Defer_(enumerableFactory);
  23. }
  24. private static IEnumerable<TSource> Defer_<TSource>(Func<IEnumerable<TSource>> enumerableFactory)
  25. {
  26. /*
  27. foreach (var item in enumerableFactory())
  28. {
  29. yield return item;
  30. }
  31. */
  32. return new DeferEnumerable<TSource>(enumerableFactory);
  33. }
  34. private sealed class DeferEnumerable<TSource> : IEnumerable<TSource>
  35. {
  36. readonly Func<IEnumerable<TSource>> _enumerableFactory;
  37. public DeferEnumerable(Func<IEnumerable<TSource>> enumerableFactory)
  38. {
  39. _enumerableFactory = enumerableFactory;
  40. }
  41. public IEnumerator<TSource> GetEnumerator()
  42. {
  43. return _enumerableFactory().GetEnumerator();
  44. }
  45. IEnumerator IEnumerable.GetEnumerator()
  46. {
  47. return GetEnumerator();
  48. }
  49. }
  50. }
  51. }