While.cs 1.5 KB

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