Defer.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. return new DeferEnumerable<TSource>(enumerableFactory);
  27. }
  28. private sealed class DeferEnumerable<TSource> : IEnumerable<TSource>
  29. {
  30. private readonly Func<IEnumerable<TSource>> _enumerableFactory;
  31. public DeferEnumerable(Func<IEnumerable<TSource>> enumerableFactory)
  32. {
  33. _enumerableFactory = enumerableFactory;
  34. }
  35. public IEnumerator<TSource> GetEnumerator()
  36. {
  37. return _enumerableFactory().GetEnumerator();
  38. }
  39. IEnumerator IEnumerable.GetEnumerator()
  40. {
  41. return GetEnumerator();
  42. }
  43. }
  44. }
  45. }