Defer.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  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.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class EnumerableEx
  11. {
  12. /// <summary>
  13. /// Creates an enumerable sequence based on an enumerable factory function.
  14. /// </summary>
  15. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  16. /// <param name="enumerableFactory">Enumerable factory function.</param>
  17. /// <returns>Sequence that will invoke the enumerable factory upon a call to GetEnumerator.</returns>
  18. public static IEnumerable<TResult> Defer<TResult>(Func<IEnumerable<TResult>> enumerableFactory)
  19. {
  20. if (enumerableFactory == null)
  21. throw new ArgumentNullException(nameof(enumerableFactory));
  22. return Defer_(enumerableFactory);
  23. }
  24. private static IEnumerable<TSource> Defer_<TSource>(Func<IEnumerable<TSource>> enumerableFactory)
  25. {
  26. foreach (var item in enumerableFactory())
  27. yield return item;
  28. }
  29. }
  30. }