Defer.cs 1.2 KB

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