While.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  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. /// Generates an enumerable sequence by repeating a source sequence as long as the given loop condition holds.
  11. /// </summary>
  12. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  13. /// <param name="condition">Loop condition.</param>
  14. /// <param name="source">Sequence to repeat while the condition evaluates true.</param>
  15. /// <returns>Sequence generated by repeating the given sequence while the condition evaluates to true.</returns>
  16. public static IEnumerable<TResult> While<TResult>(Func<bool> condition, IEnumerable<TResult> source)
  17. {
  18. if (condition == null)
  19. throw new ArgumentNullException(nameof(condition));
  20. if (source == null)
  21. throw new ArgumentNullException(nameof(source));
  22. return WhileCore(condition, source)
  23. .Concat();
  24. }
  25. private static IEnumerable<IEnumerable<TSource>> WhileCore<TSource>(Func<bool> condition, IEnumerable<TSource> source)
  26. {
  27. while (condition())
  28. yield return source;
  29. }
  30. }
  31. }